<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>北美城市天气预报</title>
    <!-- 本地化Chart.js -->
    <script src="js/chart.min.js"></script>
    <!-- 本地化XLSX库 -->
    <script src="js/xlsx.full.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            padding: 0;
            background-color: #f5f5f5;
            display: flex;
            flex-direction: column;
            align-items: stretch;
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 20px;
        }
        .controls {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
            justify-content: center;
            width: 100%;
            position: relative;
        }
        .controls input, .controls button, .controls select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .controls button {
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .controls button:hover {
            background-color: #45a049;
        }
        .controls button.delete {
            background-color: #f44336;
        }
        .controls button.delete:hover {
            background-color: #d32f2f;
        }
        .controls button.config {
            background-color: #2196F3;
        }
        .controls button.config:hover {
            background-color: #0b7dda;
        }
        .date-range {
            display: flex;
            gap: 10px;
            align-items: center;
            flex-wrap: wrap;
            justify-content: center;
        }
        .weather-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            background-color: white;
            overflow-x: auto;
        }
        .weather-table th,
        .weather-table td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: center;
        }
        .weather-table th {
            background-color: #4CAF50;
            color: white;
            font-weight: bold;
            position: sticky;
            top: 0;
        }
        .weather-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .weather-table tr:hover {
            background-color: #f0f0f0;
        }
        .loading {
            text-align: center;
            padding: 20px;
            font-size: 18px;
            color: #666;
        }
        .temp-cold {
            background-color: #ffcccc; /* 低于0度 - 红色 */
        }
        .temp-cool {
            background-color: #fff8cc; /* 0-5度 - 黄色 */
        }
        .temp-sudden-change {
            border: 2px solid #ff0000 !important;
            box-shadow: 0 0 10px rgba(255, 0, 0, 0.5) !important;
            animation: pulse 2s infinite;
        }
        .temperature-sudden-change-row {
            background-color: #fff0f0 !important;
            border-left: 4px solid #ff0000 !important;
        }
        @keyframes pulse {
            0% { box-shadow: 0 0 5px rgba(255, 0, 0, 0.5); }
            50% { box-shadow: 0 0 15px rgba(255, 0, 0, 0.8); }
            100% { box-shadow: 0 0 5px rgba(255, 0, 0, 0.5); }
        }
        .weather-icon {
            font-size: 18px;
            margin-right: 5px;
        }
        .legend {
            display: flex;
            justify-content: center;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }
        .legend-item {
            display: flex;
            align-items: center;
            margin: 0 10px;
        }
        .legend-color {
            width: 20px;
            height: 20px;
            margin-right: 5px;
            border: 1px solid #ddd;
        }
        .city-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .delete-city {
            background: none;
            border: none;
            color: white;
            cursor: pointer;
            font-size: 14px;
            padding: 2px 5px;
            border-radius: 3px;
        }
        .delete-city:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }
        .message {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            text-align: center;
            width: 100%;
        }
        .message.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .message.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .autocomplete-container {
            position: relative;
            width: 300px;
        }
        .autocomplete-list {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #ddd;
            border-top: none;
            border-radius: 0 0 4px 4px;
            max-height: 200px;
            overflow-y: auto;
            z-index: 1000;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .autocomplete-item {
            padding: 8px 12px;
            cursor: pointer;
            border-bottom: 1px solid #f0f0f0;
        }
        .autocomplete-item:hover {
            background-color: #f5f5f5;
        }
        .autocomplete-item:last-child {
            border-bottom: none;
        }
        .city-info {
            font-size: 14px;
        }
        .city-name {
            font-weight: bold;
        }
        .city-details {
            color: #666;
            font-size: 12px;
            margin-top: 2px;
        }
        .date-presets {
            display: flex;
            gap: 5px;
            margin-bottom: 10px;
        }
        .date-presets button {
            padding: 5px 10px;
            font-size: 12px;
        }
        .data-source {
            margin-top: 10px;
            font-size: 12px;
            color: #666;
            text-align: center;
        }
        .mode-indicator {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            margin-left: 10px;
            font-size: 12px;
            font-weight: bold;
        }
        .mode-past {
            background-color: #e0e0e0;
            color: #555;
        }
        .mode-future {
            background-color: #e3f2fd;
            color: #1565c0;
        }
        .compare-checkbox {
            display: flex;
            align-items: center;
            gap: 5px;
            margin-left: 15px;
        }
        .year-indicator {
            font-weight: bold;
            font-size: 14px;
            margin: 5px 0;
        }
        .current-year {
            color: #1976d2;
        }
        .last-year {
            color: #d32f2f;
        }
        .comparison-row {
            background-color: #f5f5f5;
        }
        .comparison-header {
            background-color: #e0e0e0;
            font-weight: bold;
        }
        .tab-container {
            width: 100%;
            margin-top: 20px;
        }
        .tab-header {
            display: flex;
            border-bottom: 1px solid #ddd;
        }
        .tab-button {
            padding: 10px 20px;
            background: none;
            border: none;
            cursor: pointer;
            font-size: 16px;
            border-bottom: 3px solid transparent;
            transition: all 0.3s;
        }
        .tab-button.active {
            border-bottom: 3px solid #4CAF50;
            font-weight: bold;
            color: #4CAF50;
        }
        .tab-content {
            display: none;
            padding: 0;
        }
        .tab-content.active {
            display: block;
        }
        
        /* 地图标签页特定样式 */
        #map-tab {
            height: 85vh;
        }
        .chart-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        .chart-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 15px;
        }
        .chart-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 10px;
            text-align: center;
        }
        .chart-wrapper {
            position: relative;
            height: 300px;
        }
        .config-buttons {
            display: flex;
            gap: 10px;
            margin-left: 15px;
        }
        .file-input {
            display: none;
        }
        .config-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            background-color: white;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            position: relative; /* 为子元素提供定位上下文 */
        }
        .config-table th,
        .config-table td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: center;
        }
        .config-table th {
            background-color: #4CAF50;
            color: white;
            font-weight: bold;
        }
        .config-table td {
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .config-table td:hover {
            background-color: #f0f0f0;
        }
        .config-table td.editing {
            background-color: #e3f2fd;
            padding: 0;
        }
        .config-table input {
            width: 100%;
            height: 100%;
            border: none;
            padding: 10px;
            box-sizing: border-box;
            text-align: center;
            background: transparent;
        }
        .config-table input:focus {
            outline: 2px solid #4CAF50;
        }
        .save-tip {
            position: fixed;
            background-color: #4CAF50;
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 12px;
            z-index: 10000;
            pointer-events: none;
            opacity: 0;
            transition: opacity 0.3s;
        }
        .save-tip.show {
            opacity: 1;
        }
        .city-tooltip {
            position: absolute;
            background-color: #333;
            color: white;
            padding: 8px 12px;
            border-radius: 4px;
            font-size: 12px;
            z-index: 10000;
            pointer-events: none;
            opacity: 0;
            transition: opacity 0.3s;
            max-width: 250px;
            white-space: nowrap;
        }
        .city-tooltip.show {
            opacity: 0.9;
        }
        .config-delete-btn {
            background-color: #f44336;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
        }
        .config-delete-btn:hover {
            background-color: #d32f2f;
        }
        
        /* 拖放相关样式 */
        .drag-handle {
            cursor: move;
            user-select: none;
            text-align: center;
            font-size: 16px;
            color: #999;
        }
        
        .dragging {
            opacity: 0.5;
            background-color: #f0f8ff;
        }
        
        .drag-over {
            background-color: #e6f3ff;
            border-top: 2px solid #4CAF50;
        }
        
        #drag-insert-indicator {
            position: absolute;
            color: #4CAF50;
            font-size: 16px; /* 减小箭头大小 */
            z-index: 1000;
            pointer-events: none;
            transition: top 0.2s ease;
            /* 确保相对于表格容器定位 */
            position: absolute;
            font-weight: bold; /* 使箭头更粗 */
        }
        
        /* 添加序号标注样式 */
        .city-marker-label {
            background: #4CAF50;
            border: 2px solid #ffffff;
            border-radius: 50%;
            width: 28px;
            height: 28px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 15px;
            color: white;
            box-shadow: 0 3px 8px rgba(0,0,0,0.6);
            cursor: pointer;
            z-index: 100;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.7);
            transition: all 0.3s ease;
        }

        .city-marker-label:hover {
            transform: scale(1.3);
            transition: transform 0.2s;
            background: #45a049;
            box-shadow: 0 4px 12px rgba(0,0,0,0.7);
        }
        
        /* 右键菜单样式 - 修复定位和层级问题 */
        #map-context-menu {
            position: fixed !important; /* 使用fixed定位，不受父元素影响 */
            background: white;
            border: 1px solid #ccc;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            z-index: 99999 !important; /* 提高z-index确保在最前面 */
            display: none;
            min-width: 250px;
            max-width: 300px;
            font-family: Arial, sans-serif;
            font-size: 14px;
            overflow: hidden;
            pointer-events: auto; /* 确保可以交互 */
        }

        /* 编辑名称样式 */
        .edit-name-container {
            margin-top: 8px;
            padding: 8px;
            border-top: 1px solid #eee;
        }

        .edit-name-input {
            width: 100%;
            padding: 4px 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 12px;
            margin-bottom: 4px;
        }

        .edit-name-buttons {
            display: flex;
            gap: 4px;
            margin-top: 4px;
        }

        .edit-name-btn {
            flex: 1;
            padding: 2px 4px;
            font-size: 11px;
            border: 1px solid #ddd;
            border-radius: 3px;
            background: #f5f5f5;
            cursor: pointer;
        }

        .edit-name-btn:hover {
            background: #e5e5e5;
        }

        .edit-name-btn.primary {
            background: #007bff;
            color: white;
            border-color: #007bff;
        }

        .edit-name-btn.primary:hover {
            background: #0056b3;
        }

        /* 编辑名称样式 */
        .edit-name-container {
            margin-top: 8px;
            padding: 8px;
            border-top: 1px solid #eee;
        }

        .edit-name-input {
            width: 100%;
            padding: 4px 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 12px;
            margin-bottom: 4px;
        }

        .edit-name-buttons {
            display: flex;
            gap: 4px;
            margin-top: 4px;
        }

        .edit-name-btn {
            flex: 1;
            padding: 2px 4px;
            font-size: 11px;
            border: 1px solid #ddd;
            border-radius: 3px;
            background: #f5f5f5;
            cursor: pointer;
        }

        .edit-name-btn:hover {
            background: #e5e5e5;
        }

        .edit-name-btn.primary {
            background: #007bff;
            color: white;
            border-color: #007bff;
        }

        .edit-name-btn.primary:hover {
            background: #0056b3;
        }

        /* 确保地图容器不会遮挡右键菜单 */
        #map-container {
            z-index: 1;
        }

        /* 右键菜单按钮样式 - 确保按钮可点击 */
        #context-menu-add-btn {
            z-index: 100000 !important;
            position: relative;
        }
        
        #map-context-menu .menu-header {
            padding: 12px 16px;
            border-bottom: 1px solid #eee;
            font-weight: bold;
            background: #f8f9fa;
            color: #333;
        }
        
        #map-context-menu .menu-content {
            padding: 16px;
            text-align: center;
        }
        
        #map-context-menu .menu-footer {
            padding: 12px 16px;
            border-top: 1px solid #eee;
            text-align: center;
            background: #f8f9fa;
        }
        
        #map-context-menu .weather-icon-large {
            font-size: 32px;
            margin-bottom: 8px;
        }
        
        #map-context-menu .weather-text {
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
        }
        
        #map-context-menu .temperature {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            margin-bottom: 12px;
        }
        
        #map-context-menu .add-city-btn {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: background-color 0.3s;
        }
        
        #map-context-menu .add-city-btn:hover {
            background: #45a049;
        }
        
        #map-context-menu .loading-text {
            color: #666;
            font-style: italic;
        }
        
        #map-context-menu .error-text {
            color: #f44336;
            font-size: 12px;
        }
        /* 地图样式 */
        #map-container {
            width: 100%;
            height: 80vh; /* 设置为视口高度的80% */
            margin-top: 20px;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            position: relative;
        }
        
        .map-zoom-tip {
            position: absolute;
            top: 10px;
            right: 10px;
            background: rgba(255, 255, 255, 0.9);
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 8px 12px;
            font-size: 12px;
            color: #666;
            z-index: 1000;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            max-width: 200px;
        }
        
        .map-zoom-tip .tip-title {
            font-weight: bold;
            margin-bottom: 4px;
            color: #333;
        }
        
        .map-zoom-tip .tip-item {
            margin: 2px 0;
        }
        .map-info-window {
            min-width: 250px;
            padding: 10px;
        }
        .map-info-title {
            font-weight: bold;
            margin-bottom: 10px;
            font-size: 16px;
            text-align: center;
        }
        .map-chart-container {
            height: 200px;
            width: 100%;
        }
        .map-temperature {
            font-size: 14px;
            margin: 5px 0;
            text-align: center;
        }
        .map-weather-icon {
            font-size: 24px;
            text-align: center;
            margin: 5px 0;
        }
        .map-controls {
            display: flex;
            justify-content: center;
            margin: 10px 0;
            gap: 10px;
        }
        .map-controls button {
            padding: 5px 10px;
            font-size: 12px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        .map-controls button:hover {
            background-color: #45a049;
        }
        
        /* 分析页面样式 */
        .analysis-controls {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .analysis-section {
            margin-bottom: 20px;
        }
        
        .analysis-section h3 {
            margin-bottom: 10px;
            color: #333;
            border-bottom: 2px solid #4CAF50;
            padding-bottom: 5px;
        }
        
        .temp-range-config {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            margin-bottom: 15px;
        }
        
        .temp-range-item {
            flex: 1;
            min-width: 200px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background: #f9f9f9;
        }
        
        .temp-range-item label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }
        
        .temp-range-item input {
            width: 100%;
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 3px;
        }
        
        .temp-range-actions {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }
        
        .temp-range-actions button {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .btn-add {
            background-color: #4CAF50;
            color: white;
        }
        
        .btn-add:hover {
            background-color: #45a049;
        }
        
        .btn-reset {
            background-color: #9E9E9E;
            color: white;
        }
        
        .btn-reset:hover {
            background-color: #757575;
        }
        
        .btn-remove {
            background-color: #f44336;
            color: white;
            padding: 2px 8px;
            font-size: 12px;
            margin-left: 10px;
        }
        
        .btn-remove:hover {
            background-color: #d32f2f;
        }
        
        .percentile-config {
            display: flex;
            gap: 20px;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .percentile-item {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .percentile-item label {
            font-weight: bold;
            color: #555;
        }
        
        .percentile-item input {
            width: 80px;
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 3px;
        }
        
        .analysis-results {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .city-analysis {
            margin-bottom: 30px;
            padding: 15px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            background: #fafafa;
        }
        
        .city-analysis h4 {
            margin-top: 0;
            color: #2196F3;
            border-bottom: 1px solid #2196F3;
            padding-bottom: 8px;
        }
        
        .analysis-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
            margin-bottom: 15px;
        }
        
        .analysis-card {
            background: white;
            padding: 12px;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .analysis-card h5 {
            margin: 0 0 8px 0;
            color: #666;
            font-size: 14px;
        }
        
        .analysis-value {
            font-size: 20px;
            font-weight: bold;
            color: #333;
        }
        
        .temp-range-stats {
            margin-top: 15px;
        }
        
        .temp-range-stats table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .temp-range-stats th,
        .temp-range-stats td {
            padding: 8px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        
        .temp-range-stats th {
            background-color: #f5f5f5;
            font-weight: bold;
        }
        
        .temp-range-stats .range-name {
            font-weight: bold;
        }
        
        .progress-bar {
            height: 20px;
            background-color: #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
            position: relative;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #4CAF50, #8BC34A);
            transition: width 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 12px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <h1>北美主要城市天气预报</h1>
    
    <div class="legend">
        <div class="legend-item">
            <div class="legend-color" style="background-color: #ffcccc;"></div>
            <span>温度低于0°C</span>
        </div>
        <div class="legend-item">
            <div class="legend-color" style="background-color: #fff8cc;"></div>
            <span>温度0-5°C</span>
        </div>
    </div>
    
    <div class="controls">
        <div class="autocomplete-container">
            <input type="text" id="cityInput" placeholder="输入英文地区名称，如: Vancouver">
            <div class="autocomplete-list" id="autocompleteList" style="display: none;"></div>
        </div>
        <button id="addCityBtn">添加城市</button>
        <button id="resetCitiesBtn" class="delete">重置为默认城市</button>
        <div class="config-buttons">
            <button id="exportConfigBtn" class="config">导出配置</button>
            <button id="importConfigBtn" class="config">导入配置</button>
            <input type="file" id="configFileInput" class="file-input" accept=".xlsx,.xls,.csv">
        </div>
    </div>
    
    <div class="date-range">
        <label for="startDate">开始日期:</label>
        <input type="date" id="startDate">
        <label for="endDate">结束日期:</label>
        <input type="date" id="endDate">
        <button id="updateDatesBtn">更新日期范围</button>
        <div class="compare-checkbox">
            <input type="checkbox" id="compareLastYear">
            <label for="compareLastYear">对比去年</label>
        </div>
        <span id="modeIndicator" class="mode-indicator"></span>
    </div>
    
    <div class="date-presets">
        <button id="past7DaysBtn">过去7天</button>
        <button id="past30DaysBtn">过去30天</button>
        <button id="todayBtn">今天</button>
        <button id="next7DaysBtn">未来7天</button>
        <button id="next15DaysBtn">未来15天</button>
        <!-- 添加导出按钮 -->
        <button id="exportTempDataBtn">导出温度数据</button>
        <button id="exportWeatherDataBtn">导出天气数据</button>
    </div>
    
    <div id="messageArea"></div>
    <div class="tab-container">
        <div class="tab-header">
            <button class="tab-button active" data-tab="list">列表</button>
            <button class="tab-button" data-tab="trend">趋势</button>
            <button class="tab-button" data-tab="map">地图</button>
            <button class="tab-button" data-tab="analysis">分析</button>
            <button class="tab-button" data-tab="config">配置</button>
        </div>
        
        <div id="app">
            <div class="tab-content active" id="list-tab">
                <div class="loading" id="loading">正在加载数据...</div>
                <table class="weather-table" id="weatherTable" style="display: none;">
                    <thead>
                        <tr>
                            <th>日期</th>
                            <!-- 城市列将通过 JavaScript 动态添加 -->
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <!-- 数据行将通过 JavaScript 动态添加 -->
                    </tbody>
                </table>
                <div class="data-source" id="dataSource"></div>
            </div>
            
            <div class="tab-content" id="trend-tab">
                <div class="loading" id="trendLoading">正在生成趋势图表...</div>
                <div class="chart-container" id="chartContainer"></div>
            </div>
            
            <div class="tab-content" id="map-tab">
                <div class="loading" id="mapLoading">正在加载地图...</div>
                <div id="map-container"></div>
            </div>
            
            <div class="tab-content" id="analysis-tab">
                <div class="analysis-controls">
                    <div class="analysis-section">
                        <h3>🌡️ 温度带设置</h3>
                        <div id="tempRangesContainer"></div>
                        <div class="temp-range-actions">
                            <button class="btn-add" id="addTempRangeBtn">添加温度带</button>
                            <button class="btn-reset" id="resetTempRangesBtn">恢复默认</button>
                        </div>
                    </div>
                    
                    <div class="analysis-section">
                        <h3>📊 百分位数设置</h3>
                        <div class="percentile-config">
                            <div class="percentile-item">
                                <label>最高温百分位:</label>
                                <input type="number" id="maxTempPercentile" min="1" max="100" value="85">
                                <span>%</span>
                            </div>
                            <div class="percentile-item">
                                <label>最低温百分位:</label>
                                <input type="number" id="minTempPercentile" min="1" max="100" value="85">
                                <span>%</span>
                            </div>
                            <button class="btn-add" id="analyzeBtn" style="margin-left: auto;">开始分析</button>
                        </div>
                    </div>
                </div>
                
                <div class="analysis-results" id="analysisResults">
                    <p style="text-align: center; color: #999;">请点击“开始分析”按钮进行天气分析</p>
                </div>
            </div>
            
            <div class="tab-content" id="config-tab">
                <div class="config-info">
                    <h3>城市配置信息</h3>
                    <p>双击单元格可编辑内容，失去焦点后自动保存</p>
                    <table class="config-table">
                        <thead>
                            <tr>
                                <th>排序</th>
                                <th>国家</th>
                                <th>省份</th>
                                <th>城市</th>
                                <th>地区</th>
                                <th>中文地区</th>
                                <th>经度</th>
                                <th>纬度</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="configTableBody">
                            <!-- 配置信息将通过 JavaScript 动态添加 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- 保存提示 -->
    <div class="save-tip" id="saveTip">保存成功</div>

    <!-- 城市信息提示 -->
    <div class="city-tooltip" id="cityTooltip"></div>

    <script>
        // 默认城市信息：名称、纬度、经度
        const defaultCities = [
            { name: "Vancouver", lat: 49.2827, lon: -123.1207, country: "Canada", admin1: "British Columbia", admin2: "Metro Vancouver", chineseName: "温哥华" },
            { name: "San Francisco", lat: 37.7749, lon: -122.4194, country: "United States", admin1: "California", admin2: "San Francisco County", chineseName: "旧金山" },
            { name: "Los Angeles", lat: 34.0522, lon: -118.2437, country: "United States", admin1: "California", admin2: "Los Angeles County", chineseName: "洛杉矶" },
            { name: "Edmonton", lat: 53.5461, lon: -113.4938, country: "Canada", admin1: "Alberta", admin2: "Edmonton Metropolitan Region", chineseName: "埃德蒙顿" },
            { name: "Chicago", lat: 41.8781, lon: -87.6298, country: "United States", admin1: "Illinois", admin2: "Cook County", chineseName: "芝加哥" },
            { name: "Houston", lat: 29.7604, lon: -95.3698, country: "United States", admin1: "Texas", admin2: "Harris County", chineseName: "休斯敦" },
            { name: "Ottawa", lat: 45.4215, lon: -75.6972, country: "Canada", admin1: "Ontario", admin2: "Ottawa-Carleton", chineseName: "渥太华" },
            { name: "Montreal", lat: 45.5017, lon: -73.5673, country: "Canada", admin1: "Quebec", admin2: "Montreal Urban Community", chineseName: "蒙特利尔" },
            { name: "New York", lat: 40.7128, lon: -74.0060, country: "United States", admin1: "New York", admin2: "New York County", chineseName: "纽约" },
            { name: "Washington", lat: 38.9072, lon: -77.0369, country: "United States", admin1: "District of Columbia", admin2: "Washington", chineseName: "华盛顿" },
            { name: "Miami", lat: 25.7617, lon: -80.1918, country: "United States", admin1: "Florida", admin2: "Miami-Dade County", chineseName: "迈阿密" }
        ];



        // 完整的天气代码映射（基于Open-Meteo官方文档）
        const weatherCodeMap = {
            0: { text: "晴", icon: "☀️" },
            1: { text: "晴间少云", icon: "🌤️" },
            2: { text: "晴间多云", icon: "⛅" },
            3: { text: "多云", icon: "☁️" },
            45: { text: "雾", icon: "🌫️" },
            48: { text: "冻雾", icon: "🌫️❄️" },
            51: { text: "小雨", icon: "🌦️" },
            53: { text: "中雨", icon: "🌧️" },
            55: { text: "大雨", icon: "⛈️" },
            56: { text: "冻毛毛雨", icon: "🌧️❄️" },
            57: { text: "浓冻毛毛雨", icon: "🌧️❄️" },
            61: { text: "小雨", icon: "🌦️" },
            63: { text: "中雨", icon: "🌧️" },
            65: { text: "大雨", icon: "⛈️" },
            66: { text: "冻雨", icon: "🌧️❄️" },
            67: { text: "浓冻雨", icon: "🌧️❄️" },
            71: { text: "小雪", icon: "🌨️" },
            73: { text: "中雪", icon: "❄️" },
            75: { text: "大雪", icon: "🌨️❄️" },
            77: { text: "冰粒", icon: "🧊" },
            80: { text: "小雨阵雨", icon: "🌦️" },
            81: { text: "中雨阵雨", icon: "🌧️" },
            82: { text: "大雨阵雨", icon: "⛈️" },
            85: { text: "小雪阵雨", icon: "🌨️" },
            86: { text: "大雪阵雨", icon: "🌨️❄️" },
            95: { text: "雷暴", icon: "⛈️" },
            96: { text: "雷暴伴有小冰雹", icon: "⛈️🧊" },
            99: { text: "雷暴伴有大冰雹", icon: "⛈️🧊🧊" }
        };

        // 从localStorage获取城市列表，如果没有则使用默认列表
        function getCities() {
            const savedCities = localStorage.getItem('weatherCities');
            if (savedCities) {
                return JSON.parse(savedCities);
            } else {
                // 保存默认城市到localStorage
                saveCities(defaultCities);
                return defaultCities;
            }
        }

        // 保存城市列表到localStorage
        function saveCities(cities) {
            localStorage.setItem('weatherCities', JSON.stringify(cities));
        }

        // 显示消息
        function showMessage(message, type = 'success') {
            const messageArea = document.getElementById('messageArea');
            messageArea.innerHTML = `<div class="message ${type}">${message}</div>`;
            setTimeout(() => {
                messageArea.innerHTML = '';
            }, 3000);
        }

        // 显示保存提示
        function showSaveTip(x, y) {
            const tip = document.getElementById('saveTip');
            tip.style.left = (x - 30) + 'px';
            tip.style.top = (y - 40) + 'px';
            tip.classList.add('show');
            
            setTimeout(() => {
                tip.classList.remove('show');
            }, 1500);
        }

        // 显示城市信息提示
        function showCityTooltip(city, x, y) {
            const tooltip = document.getElementById('cityTooltip');
            tooltip.innerHTML = `
                <div><strong>${city.chineseName || city.name}</strong></div>
                <div>国家: ${city.country || '未知'}</div>
                <div>省份: ${city.admin1 || '未知'}</div>
                <div>城市: ${city.admin2 || '未知'}</div>
                <div>地区: ${city.name}</div>
                <div>经度: ${city.lon}</div>
                <div>纬度: ${city.lat}</div>
            `;
            tooltip.style.left = (x + 15) + 'px';
            tooltip.style.top = (y + 15) + 'px';
            tooltip.classList.add('show');
        }

        // 隐藏城市信息提示
        function hideCityTooltip() {
            const tooltip = document.getElementById('cityTooltip');
            tooltip.classList.remove('show');
        }

        // 格式化日期为 "YYYY-MM-DD"
        function formatDate(date) {
            return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
        }

        // 获取日期范围内的所有日期（使用GMT时区）
        function getDateRange(startDate, endDate) {
            const dates = [];
            const currentDate = new Date(startDate + 'T00:00:00Z'); // 使用UTC时间
            const end = new Date(endDate + 'T00:00:00Z'); // 使用UTC时间
            
            while (currentDate <= end) {
                // 使用ISO格式的日期，与API返回格式一致
                dates.push(currentDate.toISOString().split('T')[0]);
                currentDate.setDate(currentDate.getDate() + 1);
            }
            
            return dates;
        }

        // 获取去年同期的日期范围
        function getLastYearDateRange(startDate, endDate) {
            const start = new Date(startDate);
            const end = new Date(endDate);
            
            // 减去一年
            start.setFullYear(start.getFullYear() - 1);
            end.setFullYear(end.getFullYear() - 1);
            
            return {
                start: formatDate(start),
                end: formatDate(end)
            };
        }

        // 初始化表格头部（添加城市列）
        function initTableHeader() {
            const theadTr = document.querySelector("#weatherTable thead tr");
            // 清空现有的城市列（保留日期列）
            while (theadTr.children.length > 1) {
                theadTr.removeChild(theadTr.lastChild);
            }
            
            const compareLastYear = document.getElementById('compareLastYear').checked;
            
            cities.forEach(city => {
                if (compareLastYear) {
                    // 对比模式下，每个城市有两列：今年和去年
                    const thCurrent = document.createElement("th");
                    const cityHeaderCurrent = document.createElement("div");
                    cityHeaderCurrent.className = "city-header";
                    
                    const cityNameCurrent = document.createElement("span");
                    cityNameCurrent.textContent = `${city.chineseName || city.name} (今年)`;
                    cityNameCurrent.className = "current-year";
                    
                    const deleteBtn = document.createElement("button");
                    deleteBtn.className = "delete-city";
                    deleteBtn.innerHTML = "×";
                    deleteBtn.title = "删除城市";
                    deleteBtn.addEventListener("click", (e) => {
                        e.stopPropagation();
                        deleteCity(city.name);
                    });
                    
                    cityHeaderCurrent.appendChild(cityNameCurrent);
                    cityHeaderCurrent.appendChild(deleteBtn);
                    thCurrent.appendChild(cityHeaderCurrent);
                    theadTr.appendChild(thCurrent);
                    
                    // 添加鼠标悬停事件显示城市信息
                    thCurrent.addEventListener('mouseenter', (e) => {
                        showCityTooltip(city, e.pageX, e.pageY);
                    });
                    
                    thCurrent.addEventListener('mousemove', (e) => {
                        showCityTooltip(city, e.pageX, e.pageY);
                    });
                    
                    thCurrent.addEventListener('mouseleave', hideCityTooltip);
                    
                    // 去年列
                    const thLast = document.createElement("th");
                    const cityHeaderLast = document.createElement("div");
                    cityHeaderLast.className = "city-header";
                    
                    const cityNameLast = document.createElement("span");
                    cityNameLast.textContent = `${city.chineseName || city.name} (去年)`;
                    cityNameLast.className = "last-year";
                    
                    cityHeaderLast.appendChild(cityNameLast);
                    thLast.appendChild(cityHeaderLast);
                    theadTr.appendChild(thLast);
                    
                    // 添加鼠标悬停事件显示城市信息
                    thLast.addEventListener('mouseenter', (e) => {
                        showCityTooltip(city, e.pageX, e.pageY);
                    });
                    
                    thLast.addEventListener('mousemove', (e) => {
                        showCityTooltip(city, e.pageX, e.pageY);
                    });
                    
                    thLast.addEventListener('mouseleave', hideCityTooltip);
                } else {
                    // 普通模式下，每个城市只有一列
                    const th = document.createElement("th");
                    const cityHeader = document.createElement("div");
                    cityHeader.className = "city-header";
                    
                    const cityName = document.createElement("span");
                    cityName.textContent = city.chineseName || city.name;
                    
                    const deleteBtn = document.createElement("button");
                    deleteBtn.className = "delete-city";
                    deleteBtn.innerHTML = "×";
                    deleteBtn.title = "删除城市";
                    deleteBtn.addEventListener("click", (e) => {
                        e.stopPropagation();
                        deleteCity(city.name);
                    });
                    
                    cityHeader.appendChild(cityName);
                    cityHeader.appendChild(deleteBtn);
                    th.appendChild(cityHeader);
                    theadTr.appendChild(th);
                    
                    // 添加鼠标悬停事件显示城市信息
                    th.addEventListener('mouseenter', (e) => {
                        showCityTooltip(city, e.pageX, e.pageY);
                    });
                    
                    th.addEventListener('mousemove', (e) => {
                        showCityTooltip(city, e.pageX, e.pageY);
                    });
                    
                    th.addEventListener('mouseleave', hideCityTooltip);
                }
            });
        }

        // 根据温度获取对应的CSS类名
        function getTempClass(minTemp, temperatureData) {
            let className = "";
            if (minTemp < 0) {
                className = "temp-cold"; // 低于0度
            } else if (minTemp < 5) {
                className = "temp-cool"; // 0-5度
            }
            
            // 检测气温骤降
            if (temperatureData && hasTemperatureSuddenDrop(temperatureData)) {
                className += " temp-sudden-drop";
            }
            
            return className.trim();
        }

        // 更新模式指示器
        function updateModeIndicator(isFuture) {
            const indicator = document.getElementById('modeIndicator');
            if (isFuture) {
                indicator.textContent = '天气预报模式';
                indicator.className = 'mode-indicator mode-future';
            } else {
                indicator.textContent = '历史天气模式';
                indicator.className = 'mode-indicator mode-past';
            }
        }

        // 初始化配置表格
        function initConfigTable() {
            const tbody = document.getElementById("configTableBody");
            tbody.innerHTML = ""; // 清空现有内容
            
            cities.forEach((city, index) => {
                const tr = document.createElement("tr");
                tr.dataset.index = index; // 为拖放功能添加索引属性
                
                // 添加拖放区域
                const dragTd = document.createElement("td");
                dragTd.className = "drag-handle";
                dragTd.innerHTML = "⋮⋮";
                dragTd.style.cursor = "move";
                dragTd.style.userSelect = "none";
                dragTd.style.textAlign = "center";
                dragTd.style.fontSize = "16px";
                dragTd.style.color = "#999";
                dragTd.title = "拖拽以重新排序";
                tr.appendChild(dragTd);
                
                // 国家
                const countryTd = document.createElement("td");
                countryTd.textContent = city.country || "";
                countryTd.dataset.field = "country";
                countryTd.dataset.index = index;
                tr.appendChild(countryTd);
                
                // 省份
                const admin1Td = document.createElement("td");
                admin1Td.textContent = city.admin1 || "";
                admin1Td.dataset.field = "admin1";
                admin1Td.dataset.index = index;
                tr.appendChild(admin1Td);
                
                // 城市
                const admin2Td = document.createElement("td");
                admin2Td.textContent = city.admin2 || "";
                admin2Td.dataset.field = "admin2";
                admin2Td.dataset.index = index;
                tr.appendChild(admin2Td);
                
                // 地区
                const nameTd = document.createElement("td");
                nameTd.textContent = city.name;
                nameTd.dataset.field = "name";
                nameTd.dataset.index = index;
                tr.appendChild(nameTd);
                
                // 中文地区
                const chineseNameTd = document.createElement("td");
                chineseNameTd.textContent = city.chineseName || city.name;
                chineseNameTd.dataset.field = "chineseName";
                chineseNameTd.dataset.index = index;
                tr.appendChild(chineseNameTd);
                
                // 经度
                const lonTd = document.createElement("td");
                lonTd.textContent = city.lon;
                lonTd.dataset.field = "lon";
                lonTd.dataset.index = index;
                tr.appendChild(lonTd);
                
                // 纬度
                const latTd = document.createElement("td");
                latTd.textContent = city.lat;
                latTd.dataset.field = "lat";
                latTd.dataset.index = index;
                tr.appendChild(latTd);
                
                // 操作列 - 删除按钮
                const actionTd = document.createElement("td");
                const deleteBtn = document.createElement("button");
                deleteBtn.className = "config-delete-btn";
                deleteBtn.textContent = "删除";
                deleteBtn.addEventListener("click", () => {
                    deleteCity(city.name);
                });
                actionTd.appendChild(deleteBtn);
                tr.appendChild(actionTd);
                
                tbody.appendChild(tr);
            });
            
            // 添加双击编辑功能
            addDoubleClickEdit();
            
            // 添加拖放功能
            addDragAndDrop();
        }

        // 添加双击编辑功能
        function addDoubleClickEdit() {
            const tds = document.querySelectorAll('#configTableBody td');
            
            tds.forEach(td => {
                // 跳过操作列和拖放列
                if (td.querySelector('.config-delete-btn') || td.classList.contains('drag-handle')) return;
                
                td.addEventListener('dblclick', function() {
                    // 如果是地区名，不允许编辑
                    if (this.dataset.field === 'name') return;
                    
                    const originalValue = this.textContent;
                    const field = this.dataset.field;
                    const index = parseInt(this.dataset.index);
                    
                    // 创建输入框
                    const input = document.createElement('input');
                    input.type = 'text';
                    input.value = originalValue;
                    
                    // 清空单元格内容并添加输入框
                    this.innerHTML = '';
                    this.appendChild(input);
                    this.classList.add('editing');
                    
                    // 聚焦输入框
                    input.focus();
                    input.select();
                    
                    // 保存函数
                    const save = () => {
                        const newValue = input.value.trim();
                        
                        // 验证经纬度
                        if ((field === 'lon' || field === 'lat') && isNaN(parseFloat(newValue))) {
                            showMessage('经纬度必须是数字', 'error');
                            this.textContent = originalValue;
                        } else {
                            // 更新城市数据
                            cities[index][field] = newValue;
                            saveCities(cities);
                            
                            // 更新单元格显示
                            this.textContent = newValue;
                            
                            // 显示保存提示
                            const rect = this.getBoundingClientRect();
                            showSaveTip(rect.left + rect.width / 2, rect.top);
                            
                            // 重新初始化天气表格表头，更新城市信息
                            initTableHeader();
                        }
                        
                        this.classList.remove('editing');
                    };
                    
                    // 失去焦点时保存
                    input.addEventListener('blur', save);
                    
                    // 按回车键保存
                    input.addEventListener('keydown', function(e) {
                        if (e.key === 'Enter') {
                            save();
                        } else if (e.key === 'Escape') {
                            this.textContent = originalValue;
                            this.classList.remove('editing');
                        }
                    });
                });
            });
        }
        
        // 添加拖放功能
        function addDragAndDrop() {
            const tbody = document.getElementById("configTableBody");
            const rows = tbody.querySelectorAll("tr");
            
            // 创建插入指示器
            let insertIndicator = document.getElementById('drag-insert-indicator');
            if (!insertIndicator) {
                insertIndicator = document.createElement('div');
                insertIndicator.id = 'drag-insert-indicator';
                insertIndicator.innerHTML = '▶';
                insertIndicator.style.position = 'absolute';
                insertIndicator.style.color = '#4CAF50';
                insertIndicator.style.fontSize = '20px';
                insertIndicator.style.zIndex = '1000';
                insertIndicator.style.display = 'none';
                insertIndicator.style.pointerEvents = 'none';
                // 将指示器添加到表格容器中，而不是body
                tbody.appendChild(insertIndicator);
            }
            
            rows.forEach(row => {
                const dragHandle = row.querySelector(".drag-handle");
                
                // 设置行的draggable属性
                row.setAttribute("draggable", "true");
                
                // 拖拽开始事件
                dragHandle.addEventListener("mousedown", (e) => {
                    row.setAttribute("draggable", "true");
                });
                
                row.addEventListener("dragstart", (e) => {
                    e.dataTransfer.effectAllowed = "move";
                    // 在Firefox中需要设置data
                    e.dataTransfer.setData("text/plain", row.dataset.index);
                    row.classList.add("dragging");
                    
                    // 隐藏插入指示器
                    insertIndicator.style.display = 'none';
                });
                
                row.addEventListener("dragend", (e) => {
                    row.classList.remove("dragging");
                    row.setAttribute("draggable", "false");
                    
                    // 隐藏插入指示器
                    insertIndicator.style.display = 'none';
                });
                
                // 拖拽到目标上方时的事件
                row.addEventListener("dragover", (e) => {
                    e.preventDefault();
                    e.dataTransfer.dropEffect = "move";
                    
                    // 显示插入指示器
                    const rect = row.getBoundingClientRect();
                    const tbodyRect = tbody.getBoundingClientRect();
                    const mouseY = e.clientY;
                    
                    // 判断鼠标位置是在行的上半部分还是下半部分
                    if (mouseY < rect.top + rect.height / 2) {
                        // 在行的上半部分，指示器显示在行的上方分隔线
                        insertIndicator.style.top = (rect.top - tbodyRect.top - 1) + 'px';
                    } else {
                        // 在行的下半部分，指示器显示在行的下方分隔线
                        insertIndicator.style.top = (rect.bottom - tbodyRect.top - 1) + 'px';
                    }
                    
                    insertIndicator.style.left = (rect.left - tbodyRect.left + 30) + 'px';
                    insertIndicator.style.display = 'block';
                });
                
                // 拖拽进入目标时的事件
                row.addEventListener("dragenter", (e) => {
                    e.preventDefault();
                });
                
                // 拖拽离开目标时的事件
                row.addEventListener("dragleave", (e) => {
                    // 不再移除drag-over类，因为我们要使用指示器
                });
                
                // 放置事件
                row.addEventListener("drop", (e) => {
                    e.preventDefault();
                    
                    // 隐藏插入指示器
                    insertIndicator.style.display = 'none';
                    
                    const draggedRow = document.querySelector(".dragging");
                    if (draggedRow && draggedRow !== row) {
                        const draggedIndex = parseInt(draggedRow.dataset.index);
                        const targetIndex = parseInt(row.dataset.index);
                        
                        // 判断插入位置
                        const rect = row.getBoundingClientRect();
                        const mouseY = e.clientY;
                        
                        // 计算新的插入位置
                        let newIndex = targetIndex;
                        if (mouseY >= rect.top + rect.height / 2) {
                            // 如果鼠标在行的下半部分，插入到目标行之后
                            newIndex = targetIndex + 1;
                        }
                        
                        // 如果被拖拽的元素在目标元素之前，由于移除操作会影响索引，需要调整新索引
                        if (draggedIndex < newIndex) {
                            newIndex--;
                        }
                        
                        // 只有当位置真正改变时才重新排列
                        if (draggedIndex !== newIndex) {
                            // 从原位置移除元素
                            const [movedCity] = cities.splice(draggedIndex, 1);
                            // 插入到新位置
                            cities.splice(newIndex, 0, movedCity);
                            
                            // 保存并更新界面
                            saveCities(cities);
                            initConfigTable();
                            initTableHeader();
                            initTableBody();
                            
                            showMessage("城市顺序已更新", "success");
                        }
                    }
                });
            });
        }

        // 初始化表格主体（添加日期行和数据）
        async function initTableBody() {
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            const compareLastYear = document.getElementById('compareLastYear').checked;
            
            if (!startDate || !endDate) {
                showMessage('请选择开始日期和结束日期', 'error');
                return;
            }
            
            if (new Date(startDate) > new Date(endDate)) {
                showMessage('开始日期不能晚于结束日期', 'error');
                return;
            }
            
            const today = new Date();
            today.setHours(0, 0, 0, 0); // 设置为今天的开始时间
            
            const start = new Date(startDate);
            const end = new Date(endDate);
            
            // 确定是历史数据还是预报数据
            const isFuture = start >= today;
            
            // 更新模式指示器
            updateModeIndicator(isFuture);
            
            // 如果查询过去数据但包含今天，则调整为只查询到昨天
            if (!isFuture && end >= today) {
                const yesterday = new Date(today);
                yesterday.setDate(yesterday.getDate() - 1);
                document.getElementById('endDate').value = formatDate(yesterday);
                showMessage('历史数据只能查询到昨天，已自动调整结束日期', 'success');
                return initTableBody(); // 重新调用
            }
            
            const dates = getDateRange(startDate, endDate);
            const tbody = document.getElementById("tableBody");
            tbody.innerHTML = ""; // 清空现有内容
            
            // 显示加载状态
            document.getElementById("loading").style.display = "block";
            document.getElementById("weatherTable").style.display = "none";
            
            // 获取今年数据
            const currentYearDataPromises = cities.map(city => fetchCityWeather(city, startDate, endDate, isFuture));
            
            // 如果对比去年，获取去年数据
            let lastYearDataPromises = [];
            if (compareLastYear) {
                const lastYearRange = getLastYearDateRange(startDate, endDate);
                lastYearDataPromises = cities.map(city => fetchCityWeather(city, lastYearRange.start, lastYearRange.end, false)); // 去年数据总是历史数据
            }

            // 等待所有城市的天气数据加载完成
            try {
                const allCurrentYearData = await Promise.all(currentYearDataPromises);
                let allLastYearData = [];
                
                if (compareLastYear) {
                    allLastYearData = await Promise.all(lastYearDataPromises);
                }
                
                // 检测每个城市是否有气温骤降
                const temperatureDropFlags = allCurrentYearData.map(data => 
                    data && data.temps ? hasTemperatureSuddenDrop(data.temps) : false
                );
                
                // 使用第一个城市的数据日期作为基准（所有城市应该返回相同的日期范围）
                const baseData = allCurrentYearData.find(data => data && data.dates);
                const actualDates = baseData ? baseData.dates : dates;
                
                // 为每个实际日期生成一行
                actualDates.forEach((actualDate, dateIndex) => {
                    const tr = document.createElement("tr");
                    
                    // 日期单元格
                    const dateTd = document.createElement("td");
                    dateTd.textContent = actualDate;
                    tr.appendChild(dateTd);

                    // 每个城市的天气数据单元格
                    cities.forEach((city, cityIndex) => {
                        // 当前年份数据
                        const currentData = allCurrentYearData[cityIndex];
                        const currentTd = document.createElement("td");
                        
                        // 为气温骤降的城市行添加特殊样式
                        if (temperatureDropFlags[cityIndex]) {
                            tr.classList.add('temperature-sudden-change-row');
                        }
                        
                        if (currentData && currentData.temps && currentData.weatherCodes && dateIndex < currentData.temps.length) {
                            const maxTemp = Math.round(currentData.temps[dateIndex].max);
                            const minTemp = Math.round(currentData.temps[dateIndex].min);
                            const weatherCode = currentData.weatherCodes[dateIndex];
                            const weatherInfo = weatherCodeMap[weatherCode] || { text: "未知天气", icon: "❓" };
                            
                            // 添加温度颜色标记（包含气温骤降检测）
                            currentTd.className = getTempClass(minTemp, currentData.temps);
                            
                            // 创建天气信息内容
                            const weatherContent = document.createElement("div");
                            weatherContent.innerHTML = `
                                <div><span class="weather-icon">${weatherInfo.icon}</span>${weatherInfo.text}</div>
                                <div>${maxTemp}°C/${minTemp}°C</div>
                            `;
                            currentTd.appendChild(weatherContent);
                        } else {
                            currentTd.textContent = "数据加载失败";
                        }
                        tr.appendChild(currentTd);
                        
                        // 如果对比去年，添加去年数据
                        if (compareLastYear) {
                            const lastYearData = allLastYearData[cityIndex];
                            const lastYearTd = document.createElement("td");
                            
                            // 使用去年数据的实际日期范围
                            const lastYearBaseData = allLastYearData.find(data => data && data.dates);
                            const lastYearActualDates = lastYearBaseData ? lastYearBaseData.dates : [];
                            
                            if (lastYearData && lastYearData.temps && lastYearData.weatherCodes && dateIndex < lastYearData.temps.length) {
                                const maxTemp = Math.round(lastYearData.temps[dateIndex].max);
                                const minTemp = Math.round(lastYearData.temps[dateIndex].min);
                                const weatherCode = lastYearData.weatherCodes[dateIndex];
                                const weatherInfo = weatherCodeMap[weatherCode] || { text: "未知天气", icon: "❓" };
                                
                                // 添加温度颜色标记（包含气温骤降检测）
                                lastYearTd.className = getTempClass(minTemp, lastYearData.temps);
                                
                                // 创建天气信息内容
                                const weatherContent = document.createElement("div");
                                weatherContent.innerHTML = `
                                    <div><span class="weather-icon">${weatherInfo.icon}</span>${weatherInfo.text}</div>
                                    <div>${maxTemp}°C/${minTemp}°C</div>
                                `;
                                lastYearTd.appendChild(weatherContent);
                            } else {
                                lastYearTd.textContent = "数据加载失败";
                            }
                            tr.appendChild(lastYearTd);
                        }
                    });

                    tbody.appendChild(tr);
                });

                // 隐藏加载提示，显示表格
                document.getElementById("loading").style.display = "none";
                document.getElementById("weatherTable").style.display = "table";
                
                // 显示数据来源
                let dataSource = "数据来源: ";
                if (isFuture) {
                    dataSource += "天气预报";
                } else {
                    dataSource += "历史天气数据";
                }
                
                if (compareLastYear) {
                    dataSource += " (今年) + 历史天气数据 (去年)";
                }
                
                document.getElementById("dataSource").textContent = dataSource;
                
                // 保存数据用于趋势图表
                currentWeatherData = allCurrentYearData;
                if (compareLastYear) {
                    lastYearWeatherData = allLastYearData;
                } else {
                    lastYearWeatherData = null;
                }
                
                // 如果当前显示的是趋势标签页，更新图表
                if (document.querySelector('.tab-button.active').dataset.tab === 'trend') {
                    renderTrendCharts();
                }
                
                // 如果当前显示的是地图标签页，更新地图
                if (document.querySelector('.tab-button.active').dataset.tab === 'map') {
                    renderMap();
                }
            } catch (error) {
                document.getElementById("loading").style.display = "none";
                showMessage('加载天气数据时出错: ' + error.message, 'error');
            }
        }

        // 计算温度统计信息
        function calculateTemperatureStats(temps) {
            if (!temps || temps.length === 0) {
                return {
                    totalDays: 0,
                    belowZero: { days: 0, percentage: '0.0' },
                    zeroToFive: { days: 0, percentage: '0.0' }
                };
            }
            
            const totalDays = temps.length;
            let belowZeroDays = 0;
            let zeroToFiveDays = 0;
            
            temps.forEach(temp => {
                // 使用最低温度来判断
                const minTemp = temp.min;
                
                if (minTemp < 0) {
                    belowZeroDays++;
                } else if (minTemp >= 0 && minTemp <= 5) {
                    zeroToFiveDays++;
                }
            });
            
            return {
                totalDays: totalDays,
                belowZero: {
                    days: belowZeroDays,
                    percentage: ((belowZeroDays / totalDays) * 100).toFixed(1)
                },
                zeroToFive: {
                    days: zeroToFiveDays,
                    percentage: ((zeroToFiveDays / totalDays) * 100).toFixed(1)
                }
            };
        }

        // 渲染趋势图表
        function renderTrendCharts() {
            const chartContainer = document.getElementById('chartContainer');
            const trendLoading = document.getElementById('trendLoading');
            
            // 显示加载状态
            trendLoading.style.display = 'block';
            chartContainer.innerHTML = '';
            
            // 延迟渲染，确保DOM已更新
            setTimeout(() => {
                try {
                    const compareLastYear = document.getElementById('compareLastYear').checked;
                    const dates = getDateRange(
                        document.getElementById('startDate').value,
                        document.getElementById('endDate').value
                    );
                    
                    // 为每个城市创建图表
                    cities.forEach((city, cityIndex) => {
                        const currentData = currentWeatherData[cityIndex];
                        if (!currentData || !currentData.temps) return;
                        
                        const chartCard = document.createElement('div');
                        chartCard.className = 'chart-card';
                        
                        const chartTitle = document.createElement('div');
                        chartTitle.className = 'chart-title';
                        chartTitle.textContent = (cityIndex + 1) + '. ' + (city.chineseName || city.name) + (compareLastYear ? ' (今年 vs 去年)' : '');
                        chartCard.appendChild(chartTitle);
                        
                        // 计算温度统计信息
                        const tempStats = calculateTemperatureStats(currentData.temps);
                        
                        // 创建统计信息显示
                        const statsContainer = document.createElement('div');
                        statsContainer.style.cssText = 'margin: 10px 0; padding: 10px; background-color: #f5f5f5; border-radius: 4px; font-size: 13px;';
                        statsContainer.innerHTML = `
                            <div style="display: flex; justify-content: space-around; text-align: center;">
                                <div style="flex: 1;">
                                    <div style="font-weight: bold; color: #ff6b6b;">0度以下</div>
                                    <div>${tempStats.belowZero.days}天 (${tempStats.belowZero.percentage}%)</div>
                                </div>
                                <div style="flex: 1;">
                                    <div style="font-weight: bold; color: #ffa500;">0-5度</div>
                                    <div>${tempStats.zeroToFive.days}天 (${tempStats.zeroToFive.percentage}%)</div>
                                </div>
                                <div style="flex: 1;">
                                    <div style="font-weight: bold; color: #666;">总天数</div>
                                    <div>${tempStats.totalDays}天</div>
                                </div>
                            </div>
                        `;
                        chartCard.appendChild(statsContainer);
                        
                        const chartWrapper = document.createElement('div');
                        chartWrapper.className = 'chart-wrapper';
                        chartCard.appendChild(chartWrapper);
                        
                        const canvas = document.createElement('canvas');
                        chartWrapper.appendChild(canvas);
                        
                        chartContainer.appendChild(chartCard);
                        
                        // 准备图表数据
                        const currentMaxTemps = currentData.temps.map(temp => Math.round(temp.max));
                        const currentMinTemps = currentData.temps.map(temp => Math.round(temp.min));
                        
                        const datasets = [
                            {
                                label: '最高温度',
                                data: currentMaxTemps,
                                borderColor: 'rgb(255, 99, 132)',
                                backgroundColor: 'rgba(255, 99, 132, 0.1)',
                                tension: 0.3,
                                yAxisID: 'y'
                            },
                            {
                                label: '最低温度',
                                data: currentMinTemps,
                                borderColor: 'rgb(54, 162, 235)',
                                backgroundColor: 'rgba(54, 162, 235, 0.1)',
                                tension: 0.3,
                                yAxisID: 'y'
                            }
                        ];
                        
                        // 如果有去年数据，添加去年数据
                        if (compareLastYear && lastYearWeatherData && lastYearWeatherData[cityIndex]) {
                            const lastYearData = lastYearWeatherData[cityIndex];
                            if (lastYearData && lastYearData.temps) {
                                const lastYearMaxTemps = lastYearData.temps.map(temp => Math.round(temp.max));
                                const lastYearMinTemps = lastYearData.temps.map(temp => Math.round(temp.min));
                                
                                datasets.push(
                                    {
                                        label: '去年最高温度',
                                        data: lastYearMaxTemps,
                                        borderColor: 'rgb(255, 159, 64)',
                                        backgroundColor: 'rgba(255, 159, 64, 0.1)',
                                        borderDash: [5, 5],
                                        tension: 0.3,
                                        yAxisID: 'y'
                                    },
                                    {
                                        label: '去年最低温度',
                                        data: lastYearMinTemps,
                                        borderColor: 'rgb(75, 192, 192)',
                                        backgroundColor: 'rgba(75, 192, 192, 0.1)',
                                        borderDash: [5, 5],
                                        tension: 0.3,
                                        yAxisID: 'y'
                                    }
                                );
                            }
                        }
                        
                        // 创建图表
                        new Chart(canvas, {
                            type: 'line',
                            data: {
                                labels: dates,
                                datasets: datasets
                            },
                            options: {
                                responsive: true,
                                maintainAspectRatio: false,
                                plugins: {
                                    title: {
                                        display: true,
                                        text: (cityIndex + 1) + '. ' + (city.chineseName || city.name) + ' 温度趋势'
                                    },
                                    tooltip: {
                                        mode: 'index',
                                        intersect: false
                                    }
                                },
                                scales: {
                                    x: {
                                        display: true,
                                        title: {
                                            display: true,
                                            text: '日期'
                                        }
                                    },
                                    y: {
                                        display: true,
                                        title: {
                                            display: true,
                                            text: '温度 (°C)'
                                        }
                                    }
                                }
                            }
                        });
                    });
                    
                    // 隐藏加载状态
                    trendLoading.style.display = 'none';
                } catch (error) {
                    console.error('渲染趋势图表时出错:', error);
                    trendLoading.style.display = 'none';
                    showMessage('生成趋势图表时出错: ' + error.message, 'error');
                }
            }, 100);
        }

        // 创建右键菜单
        function createContextMenu() {
            // 先清理已存在的菜单
            cleanupExistingMenu();
            
            const menu = document.createElement('div');
            menu.id = 'map-context-menu';
            
            menu.innerHTML = `
                <div class="menu-header">
                    <span>📍 位置天气预报</span>
                </div>
                <div id="context-menu-content" class="menu-content">
                    <div class="loading-text">正在获取位置信息...</div>
                </div>
                <div id="edit-name-container" class="edit-name-container" style="display: none;">
                    <input type="text" id="edit-name-input" class="edit-name-input" placeholder="输入自定义地区名称">
                    <div class="edit-name-buttons">
                        <button id="edit-name-cancel" class="edit-name-btn">取消</button>
                        <button id="edit-name-save" class="edit-name-btn primary">保存</button>
                    </div>
                </div>
                <div class="menu-footer">
                    <button id="context-menu-edit-btn" class="edit-name-btn" style="display: none; margin-bottom: 8px;">
                        编辑地区名称
                    </button>
                    <button id="context-menu-add-btn" class="add-city-btn" style="display: none;">
                        添加到城市列表
                    </button>
                </div>
            `;
            
            document.body.appendChild(menu);
            return menu;
        }

        // 显示右键菜单 - 修复定位问题
        function showContextMenu(map, point, lng, lat, event) {
            console.log('显示右键菜单', { lng, lat, event });
            
            const menu = document.getElementById('map-context-menu') || createContextMenu();
            const content = menu.querySelector('#context-menu-content');
            const addBtn = menu.querySelector('#context-menu-add-btn');
            const editBtn = menu.querySelector('#context-menu-edit-btn');
            const editContainer = menu.querySelector('#edit-name-container');
            const editInput = menu.querySelector('#edit-name-input');
            const editSaveBtn = menu.querySelector('#edit-name-save');
            const editCancelBtn = menu.querySelector('#edit-name-cancel');
            
            // 初始化编辑状态
            let currentLocationInfo = null;
            let currentWeatherData = null;
            let isEditing = false;
            
            // 编辑按钮点击事件
            editBtn.onclick = () => {
                isEditing = true;
                editContainer.style.display = 'block';
                editBtn.style.display = 'none';
                editInput.value = currentLocationInfo ? currentLocationInfo.name : '';
                editInput.focus();
            };
            
            // 保存编辑
            editSaveBtn.onclick = () => {
                const customName = editInput.value.trim();
                if (customName) {
                    if (currentLocationInfo) {
                        currentLocationInfo.name = customName;
                        currentLocationInfo.chineseName = customName;
                    }
                    updateMenuContent(currentLocationInfo, currentWeatherData);
                    
                    // 更新菜单标题显示编辑后的名称
                    const menuHeader = menu.querySelector('.menu-header span');
                    if (menuHeader && currentLocationInfo) {
                        menuHeader.textContent = `📍 ${currentLocationInfo.chineseName || currentLocationInfo.name || '未知位置'}`;
                    }
                }
                cancelEdit();
            };
            
            // 取消编辑
            editCancelBtn.onclick = cancelEdit;
            
            // 为编辑输入框添加键盘事件
            editInput.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') {
                    editSaveBtn.click();
                } else if (e.key === 'Escape') {
                    cancelEdit();
                }
            });
            
            // 取消编辑函数
            function cancelEdit() {
                isEditing = false;
                editContainer.style.display = 'none';
                editBtn.style.display = 'block';
            }
            
            // 更新菜单内容函数
            function updateMenuContent(locationInfo, weatherData) {
                if (weatherData) {
                    const weatherInfo = weatherCodeMap[weatherData.weatherCode] || { text: "未知天气", icon: "❓" };
                    
                    // 更新菜单标题显示位置信息
                    const menuHeader = menu.querySelector('.menu-header span');
                    if (menuHeader && locationInfo) {
                        menuHeader.textContent = `📍 ${locationInfo.chineseName || locationInfo.name || '未知位置'}`;
                    }
                    
                    content.innerHTML = `
                        <div class="weather-icon-large">${weatherInfo.icon}</div>
                        <div class="weather-text">${weatherInfo.text}</div>
                        <div class="temperature">
                            <div>最高: ${Math.round(weatherData.maxTemp)}°C</div>
                            <div>最低: ${Math.round(weatherData.minTemp)}°C</div>
                        </div>
                        ${locationInfo ? `<div style="font-size: 12px; color: #666; margin-top: 8px;">${locationInfo.country || ''} ${locationInfo.admin1 || ''} ${locationInfo.admin2 || ''}</div>` : ''}
                    `;
                }
            }
            
            // 先隐藏之前的菜单
            hideContextMenu();
            
            // 确保菜单样式正确
            menu.style.position = 'fixed';
            menu.style.zIndex = '10000';
            menu.style.display = 'block';
            
            // 计算菜单位置 - 修复定位逻辑
            let menuX, menuY;
            
            if (event && event.clientX && event.clientY) {
                // 优先使用鼠标事件的位置
                menuX = event.clientX;
                menuY = event.clientY;
                console.log('使用鼠标位置:', menuX, menuY);
            } else {
                // 备用：使用地图坐标转换
                try {
                    const pixel = map.pointToOverlayPixel(point);
                    const mapContainer = document.getElementById('map-container');
                    const rect = mapContainer.getBoundingClientRect();
                    menuX = rect.left + pixel.x;
                    menuY = rect.top + pixel.y;
                    console.log('使用地图坐标位置:', menuX, menuY);
                } catch (error) {
                    // 最后备用：使用屏幕中心
                    menuX = window.innerWidth / 2;
                    menuY = window.innerHeight / 2;
                    console.log('使用屏幕中心位置:', menuX, menuY);
                }
            }
            
            // 确保菜单不会超出屏幕边界
            const menuWidth = 250; // 菜单宽度
            const menuHeight = 200; // 菜单高度
            
            // 检查右边界
            if (menuX + menuWidth > window.innerWidth) {
                menuX = window.innerWidth - menuWidth - 10;
            }
            
            // 检查下边界
            if (menuY + menuHeight > window.innerHeight) {
                menuY = window.innerHeight - menuHeight - 10;
            }
            
            // 检查左边界
            if (menuX < 10) {
                menuX = 10;
            }
            
            // 检查上边界
            if (menuY < 10) {
                menuY = 10;
            }
            
            // 设置最终位置（偏移10px避免遮挡鼠标）
            menu.style.left = (menuX + 10) + 'px';
            menu.style.top = (menuY + 10) + 'px';
            
            console.log('最终菜单位置:', menu.style.left, menu.style.top);
            
            // 显示位置信息和加载状态 - 修复显示顺序
            content.innerHTML = `
                <div class="loading-text">
                    <div>📍 位置: ${lng.toFixed(4)}, ${lat.toFixed(4)}</div>
                    <div>正在获取天气信息...</div>
                </div>
            `;
            
            // 确保按钮立即显示并正确设置状态
            addBtn.style.display = 'block';
            addBtn.style.visibility = 'visible';
            addBtn.style.opacity = '1';
            addBtn.disabled = true;
            addBtn.textContent = '正在获取位置信息...';
            
            // 编辑按钮初始状态为隐藏
            editBtn.style.display = 'none';
            editBtn.style.visibility = 'hidden';
            editBtn.style.opacity = '0';
            
            // 强制重绘确保按钮显示在最前面
            menu.style.display = 'none';
            setTimeout(() => {
                menu.style.display = 'block';
            }, 10);
            
            // 并行获取天气信息和位置名称
            Promise.all([
                getWeatherForLocation(lng, lat),
                getCityNameByCoordinates(lng, lat)
            ]).then(([weatherData, locationInfo]) => {
                if (weatherData) {
                    const weatherInfo = weatherCodeMap[weatherData.weatherCode] || { text: "未知天气", icon: "❓" };
                    
                    // 保存位置信息和天气数据用于编辑功能
                    currentLocationInfo = locationInfo;
                    currentWeatherData = weatherData;
                    
                    // 更新菜单标题显示位置信息
                    const menuHeader = menu.querySelector('.menu-header span');
                    if (menuHeader && locationInfo) {
                        menuHeader.textContent = `📍 ${locationInfo.chineseName || locationInfo.name || '未知位置'}`;
                    }
                    
                    content.innerHTML = `
                        <div class="weather-icon-large">${weatherInfo.icon}</div>
                        <div class="weather-text">${weatherInfo.text}</div>
                        <div class="temperature">
                            <div>最高: ${Math.round(weatherData.maxTemp)}°C</div>
                            <div>最低: ${Math.round(weatherData.minTemp)}°C</div>
                        </div>
                        ${locationInfo ? `<div style="font-size: 12px; color: #666; margin-top: 8px;">${locationInfo.country || ''} ${locationInfo.admin1 || ''} ${locationInfo.admin2 || ''}</div>` : ''}
                    `;
                    
                    // 启用添加按钮和编辑按钮 - 修复显示问题
                    setTimeout(() => {
                        addBtn.disabled = false;
                        addBtn.textContent = '添加到城市列表';
                        addBtn.style.display = 'block';
                        addBtn.style.visibility = 'visible';
                        addBtn.style.opacity = '1';
                        
                        // 显示编辑按钮
                        editBtn.style.display = 'block';
                        editBtn.style.visibility = 'visible';
                        editBtn.style.opacity = '1';
                        
                        addBtn.onclick = () => {
                            if (currentLocationInfo) {
                                addCityByObject({
                                    name: currentLocationInfo.name,
                                    lat: lat,
                                    lon: lng,
                                    country: currentLocationInfo.country,
                                    admin1: currentLocationInfo.admin1,
                                    admin2: currentLocationInfo.admin2,
                                    chineseName: currentLocationInfo.chineseName || currentLocationInfo.name
                                });
                            } else {
                                addCityByCoordinates(lng, lat);
                            }
                            hideContextMenu();
                        };
                        
                        // 强制重绘确保按钮显示
                        addBtn.offsetHeight;
                        editBtn.offsetHeight;
                    }, 100);
                } else {
                    content.innerHTML = '<div class="error-text">获取天气信息失败，请检查网络连接</div>';
                    addBtn.style.display = 'none';
                    editBtn.style.display = 'none';
                }
            }).catch(error => {
                console.error('获取信息失败:', error);
                content.innerHTML = `
                    <div class="error-text">获取信息失败</div>
                    <div style="font-size: 12px; color: #666; margin-top: 8px;">位置: ${lng.toFixed(4)}, ${lat.toFixed(4)}</div>
                `;
                
                // 创建默认位置信息用于编辑
                currentLocationInfo = {
                    name: `位置_${lng.toFixed(4)}_${lat.toFixed(4)}`,
                    country: '',
                    admin1: '',
                    admin2: '',
                    chineseName: `位置 (${lng.toFixed(4)}, ${lat.toFixed(4)})`
                };
                
                setTimeout(() => {
                    addBtn.disabled = false;
                    addBtn.textContent = '手动添加此位置';
                    addBtn.style.display = 'block';
                    addBtn.style.visibility = 'visible';
                    addBtn.style.opacity = '1';
                    
                    // 显示编辑按钮
                    editBtn.style.display = 'block';
                    editBtn.style.visibility = 'visible';
                    editBtn.style.opacity = '1';
                    
                    addBtn.onclick = () => {
                        addCityByCoordinates(lng, lat);
                        hideContextMenu();
                    };
                    
                    // 强制重绘确保按钮显示
                    addBtn.offsetHeight;
                    editBtn.offsetHeight;
                }, 100);
            });
            
            // 设置全局菜单管理
            setupGlobalMenuHandler();
            
            // 添加ESC键隐藏菜单
            const keyHandler = (e) => {
                if (e.key === 'Escape') {
                    hideContextMenu();
                }
            };
            
            document.addEventListener('keydown', keyHandler);
            
            // 清理事件监听器
            menu._keyHandler = keyHandler;
        }

        // 隐藏右键菜单
        function hideContextMenu() {
            const menu = document.getElementById('map-context-menu');
            if (menu) {
                menu.style.display = 'none';
                // 清除所有事件监听器
                const addBtn = menu.querySelector('#context-menu-add-btn');
                if (addBtn) {
                    addBtn.onclick = null;
                }
                // 清理ESC键监听器
                if (menu._keyHandler) {
                    document.removeEventListener('keydown', menu._keyHandler);
                    menu._keyHandler = null;
                }
            }
        }

        // 检查菜单是否已存在并清理
        function cleanupExistingMenu() {
            const existingMenu = document.getElementById('map-context-menu');
            if (existingMenu && existingMenu.parentNode) {
                existingMenu.parentNode.removeChild(existingMenu);
            }
        }

        // 全局右键菜单管理
        let currentMenuHandler = null;
        
        // 添加全局点击事件监听器
        function setupGlobalMenuHandler() {
            if (currentMenuHandler) {
                document.removeEventListener('click', currentMenuHandler);
            }
            
            currentMenuHandler = function(e) {
                const menu = document.getElementById('map-context-menu');
                if (menu && menu.style.display === 'block') {
                    if (!menu.contains(e.target)) {
                        hideContextMenu();
                    }
                }
            };
            
            document.addEventListener('click', currentMenuHandler);
        }

        // 检测气温骤降（一周内最低气温变化超过5度）
        function detectTemperatureChange(temps) {
            if (!temps || temps.length < 7) return false;
            
            // 获取最近7天的最低气温
            const last7DaysMinTemps = temps.slice(-7).map(temp => temp.min);
            
            // 计算最大值和最小值
            const maxTemp = Math.max(...last7DaysMinTemps);
            const minTemp = Math.min(...last7DaysMinTemps);
            
            // 如果温差超过5度，返回true
            return (maxTemp - minTemp) > 5;
        }

        function detectTemperatureDrop(temps) {
    // 确保有足够的温度数据（至少7天）
    if (!temps || temps.length < 7) return false;
    
    // 获取最近7天的最低气温
    const last7DaysMinTemps = temps.slice(-7).map(temp => temp.min);
    
    // 检查是否存在后项温度比前项温度低超过5度的情况
    for (let i = 0; i < last7DaysMinTemps.length; i++) {
        // 只比较当前天之后的温度（确保时间顺序：后面对前面）
        for (let j = i + 1; j < last7DaysMinTemps.length; j++) {
            // 计算温差：前面的温度 - 后面的温度
            const temperatureDiff = last7DaysMinTemps[i] - last7DaysMinTemps[j];
            // 如果温差超过5度，说明出现骤降
            if (temperatureDiff > 5) {
                return true;
            }
        }
    }
    
    // 没有检测到骤降
    return false;
}


        // 检测气温骤降（一周内最低气温变化超过5度）- 与detectTemperatureChange功能相同
        function hasTemperatureSuddenDrop(temperatureData) {
            return detectTemperatureDrop(temperatureData);
        }

        // 获取指定位置的天气信息
        async function getWeatherForLocation(lng, lat) {
            const today = formatDate(new Date());
            // 使用GMT时区而不是UTC，避免时区差异导致日期不匹配
            const apiUrl = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}&daily=temperature_2m_max,temperature_2m_min,weathercode&timezone=GMT&forecast_days=1`;
            
            try {
                const response = await fetch(apiUrl);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const data = await response.json();
                
                if (data.daily && data.daily.time && data.daily.time.length > 0) {
                    return {
                        maxTemp: data.daily.temperature_2m_max[0],
                        minTemp: data.daily.temperature_2m_min[0],
                        weatherCode: data.daily.weathercode[0]
                    };
                } else {
                    throw new Error('API返回数据格式不正确');
                }
            } catch (error) {
                console.error('获取位置天气信息失败:', error);
                return null;
            }
        }

        // 通过经纬度添加城市
        async function addCityByCoordinates(lng, lat) {
            try {
                // 使用逆地理编码获取城市名称
                const cityInfo = await getCityNameByCoordinates(lng, lat);
                
                if (cityInfo) {
                    const cityData = {
                        name: cityInfo.name,
                        lat: lat,
                        lon: lng,
                        country: cityInfo.country || '',
                        admin1: cityInfo.admin1 || '',
                        admin2: cityInfo.admin2 || cityInfo.name,
                        chineseName: cityInfo.chineseName || cityInfo.name
                    };
                    
                    addCityByObject(cityData);
                } else {
                    // 如果无法获取城市名称，使用坐标作为名称
                    const cityData = {
                        name: `位置_${lng.toFixed(2)}_${lat.toFixed(2)}`,
                        lat: lat,
                        lon: lng,
                        country: '',
                        admin1: '',
                        admin2: '',
                        chineseName: `位置 (${lng.toFixed(2)}, ${lat.toFixed(2)})`
                    };
                    
                    addCityByObject(cityData);
                }
            } catch (error) {
                showMessage('添加城市失败: ' + error.message, 'error');
            }
        }

        // 通过经纬度获取城市名称 - 改进版本
        async function getCityNameByCoordinates(lng, lat) {
            // 优先使用百度地图逆地理编码（更准确）
            try {
                const geocoder = new BMap.Geocoder();
                return new Promise((resolve, reject) => {
                    geocoder.getLocation(new BMap.Point(lng, lat), (result) => {
                        if (result) {
                            const address = result.addressComponents;
                            console.log('百度地图逆地理编码结果:', address);
                            console.log('完整的result对象:', result);
                            
                            // 根据反馈的正确映射关系
                            // district -> name 和 chineseName
                            // country -> country
                            // province -> admin1  
                            // city -> admin2
                            
                            // 根据您提供的示例，国家信息在result.content.address_detail.country中
                            let countryValue = '';
                            // debugger
                            // 检查完整的结果结构
                            if (result.content && result.content.address_detail) {
                                countryValue = result.content.address_detail.country || '';
                            } 
                            
                            console.log('提取的国家信息:', countryValue);
                            
                            resolve({
                                name: address.district || address.city || address.province || '未知位置',
                                country: countryValue,
                                admin1: address.province || '',
                                admin2: address.city || address.district || '',
                                chineseName: address.district || address.city || address.province || '未知位置'
                            });
                        } else {
                            reject(new Error('百度地图逆地理编码失败'));
                        }
                    });
                });
            } catch (error) {
                console.error('百度地图逆地理编码失败:', error);
                
                // 备用方案1：使用OpenStreetMap Nominatim API
                try {
                    const apiUrl = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}&zoom=10&addressdetails=1`;
                    const response = await fetch(apiUrl);
                    if (response.ok) {
                        const data = await response.json();
                        
                        if (data.address) {
                            const address = data.address;
                            const name = address.city || address.town || address.village || address.hamlet || 
                                       address.suburb || address.county || '未知位置';
                            return {
                                name: name,
                                country: address.country || '',
                                admin1: address.state || address.province || '',
                                admin2: address.city || address.town || address.county || '',
                                chineseName: name // 英文名称作为中文名称
                            };
                        }
                    }
                } catch (osmError) {
                    console.error('OpenStreetMap逆地理编码失败:', osmError);
                }
                
                // 备用方案2：使用Open-Meteo的地理编码API
                try {
                    const geoApiUrl = `https://geocoding-api.open-meteo.com/v1/reverse?latitude=${lat}&longitude=${lng}&language=en`;
                    const geoResponse = await fetch(geoApiUrl);
                    if (geoResponse.ok) {
                        const geoData = await geoResponse.json();
                        if (geoData.results && geoData.results.length > 0) {
                            const result = geoData.results[0];
                            return {
                                name: result.name,
                                country: result.country || '',
                                admin1: result.admin1 || '',
                                admin2: result.admin2 || result.name,
                                chineseName: result.name
                            };
                        }
                    }
                } catch (geoError) {
                    console.error('Open-Meteo逆地理编码失败:', geoError);
                }
                
                // 最后备用：使用坐标生成名称
                return {
                    name: `Location_${lng.toFixed(4)}_${lat.toFixed(4)}`,
                    country: '',
                    admin1: '',
                    admin2: '',
                    chineseName: `位置 (${lng.toFixed(4)}, ${lat.toFixed(4)})`
                };
            }
        }

        // 修改地图渲染函数以添加序号标注
        // 渲染地图
        function renderMap() {
            const mapContainer = document.getElementById('map-container');
            const mapLoading = document.getElementById('mapLoading');
            
            // 显示加载状态
            mapLoading.style.display = 'block';
            mapContainer.innerHTML = '';
            
            // 延迟渲染，确保DOM已更新
            setTimeout(() => {
                try {
                    // 创建地图实例
                    const map = new BMap.Map("map-container");
                    
                    // 设置地图中心点和缩放级别
                    const point = new BMap.Point(-100, 40); // 北美中心点
                    map.centerAndZoom(point, 4);
                    
                    // 添加地图控件
                    map.addControl(new BMap.NavigationControl());
                    map.addControl(new BMap.ScaleControl());
                    map.addControl(new BMap.MapTypeControl());
                    
                    // 添加右键事件监听器 - 修复绑定方式
                    map.addEventListener('rightclick', function(e) {
                        console.log('右键事件触发', e);
                        // 阻止默认的右键菜单
                        if (e.domEvent) {
                            e.domEvent.preventDefault();
                        }
                        
                        // 显示自定义右键菜单
                        showContextMenu(map, e.point, e.point.lng, e.point.lat, e.domEvent);
                    });
                    
                    // 备用右键事件绑定（确保事件能被捕获）
                    const mapContainer = document.getElementById('map-container');
                    mapContainer.addEventListener('contextmenu', function(e) {
                        console.log('contextmenu事件触发', e);
                        e.preventDefault();
                        
                        // 将鼠标位置转换为地图坐标
                        const pixel = new BMap.Pixel(e.clientX, e.clientY);
                        const point = map.pixelToPoint(pixel);
                        const mapPoint = map.pointToMapPoint(point);
                        const lngLat = mapPointToLngLat(mapPoint);
                        
                        showContextMenu(map, point, lngLat.lng, lngLat.lat, e);
                    });
                    
                    // 辅助函数：将地图点转换为经纬度
                    function mapPointToLngLat(mapPoint) {
                        const projection = map.getMapType().getProjection();
                        if (projection) {
                            return projection.pointToLngLat(mapPoint);
                        }
                        // 备用计算方式
                        const center = map.getCenter();
                        const zoom = map.getZoom();
                        const mapSize = Math.pow(2, 18 - zoom) * 256; // 假设最大缩放级别为18
                        const lng = center.lng + (mapPoint.x - 128) / mapSize * 360;
                        const lat = center.lat - (mapPoint.y - 128) / mapSize * 180;
                        return { lng: lng, lat: lat };
                    }
                    
                    // 启用鼠标滚轮缩放功能
                    map.enableScrollWheelZoom(true);
                    map.enableContinuousZoom(true); // 启用连续缩放
                    map.enablePinchToZoom(true); // 启用双指缩放（移动设备）
                    map.enableDoubleClickZoom(true); // 启用双击缩放
                    
                    // 添加键盘快捷键支持
                    map.addEventListener('keypress', function(e) {
                        // '+' 键放大
                        if (e.key === '+' || e.key === '=') {
                            map.zoomIn();
                        }
                        // '-' 键缩小
                        else if (e.key === '-' || e.key === '_') {
                            map.zoomOut();
                        }
                    });
                    
                    // 添加缩放提示
                    const zoomTip = document.createElement('div');
                    zoomTip.className = 'map-zoom-tip';
                    zoomTip.innerHTML = `
                        <div class="tip-title">🗺️ 地图操作提示</div>
                        <div class="tip-item">• 鼠标滚轮：缩放地图</div>
                        <div class="tip-item">• 双击：快速放大</div>
                        <div class="tip-item">• +/- 键：键盘缩放</div>
                        <div class="tip-item">• 右键：查看天气预报</div>
                    `;
                    // mapContainer.appendChild(zoomTip);
                    
                    // 5秒后自动隐藏提示
                    setTimeout(() => {
                        zoomTip.style.opacity = '0.7';
                    }, 5000);
                    
                    // 鼠标悬停时显示完整提示
                    zoomTip.addEventListener('mouseenter', () => {
                        zoomTip.style.opacity = '1';
                    });
                    
                    zoomTip.addEventListener('mouseleave', () => {
                        zoomTip.style.opacity = '0.7';
                    });
                    
                    // 为每个城市添加标记 - 修改为默认显示文字标注
                    cities.forEach((city, cityIndex) => {
                        const currentData = currentWeatherData[cityIndex];
                        if (!currentData || !currentData.temps) return;
                        
                        // 创建标记点
                        const cityPoint = new BMap.Point(city.lon, city.lat);
                        
                        // 创建序号标注（显示城市在配置中的顺序）
                        const markerLabel = document.createElement('div');
                        markerLabel.className = 'city-marker-label';
                        markerLabel.textContent = cityIndex + 1; // 序号从1开始
                        markerLabel.title = `${cityIndex + 1}. ${city.chineseName || city.name}`;
                        
                        const markerLabelOverlay = new BMap.Label('', {
                            position: cityPoint,
                            offset: new BMap.Size(-12, -35) // 调整位置，使其显示在城市名称上方
                        });
                        
                        markerLabelOverlay.setStyle({
                            border: 'none',
                            background: 'none'
                        });
                        
                        markerLabelOverlay.setContent(markerLabel.outerHTML);
                        
                        // 添加序号标注到地图
                        map.addOverlay(markerLabelOverlay);
                        
                        // 创建文字标注（默认显示地区名和温度）
                        if (currentData.temps.length > 0) {
                            const todayTemp = currentData.temps[0];
                            const todayWeatherCode = currentData.weatherCodes[0];
                            const weatherInfo = weatherCodeMap[todayWeatherCode] || { text: "未知天气", icon: "❓" };
                            
                            // 检测气温骤降
                            const hasSuddenDrop = hasTemperatureSuddenDrop(currentData.temps);
                            
                            // 创建标注内容：地区名 + 当前温度（只显示文字）
                            const labelContent = `
                                <div style="background: white; border: 1px solid #ccc; border-radius: 4px; padding: 4px 8px; font-size: 12px; white-space: nowrap; box-shadow: 0 2px 4px rgba(0,0,0,0.1);${hasSuddenDrop ? ' border: 2px solid #ff0000; box-shadow: 0 0 10px rgba(255, 0, 0, 0.5); animation: pulse 2s infinite;' : ''}">
                                    <div style="font-weight: bold;">${city.chineseName || city.name}</div>
                                    <div>${Math.round(todayTemp.max)}°C ${weatherInfo.text}</div>
                                </div>
                            `;
                            
                            const label = new BMap.Label(labelContent, {
                                position: cityPoint,
                                offset: new BMap.Size(-20, -10) // 调整位置，使其显示在序号下方
                            });
                            
                            // 设置标注样式
                            label.setStyle({
                                border: 'none',
                                background: 'none'
                            });
                            
                            // 为标注添加点击事件（与标记保持一致）
                            label.addEventListener('click', function() {
                                infoWindow.setContent(infoContent);
                                map.openInfoWindow(infoWindow, cityPoint);
                            });
                            
                            // 添加标注到地图
                            map.addOverlay(label);
                        }
                        
                        // 创建标记点（保持点击事件）
                        const marker = new BMap.Marker(cityPoint);
                        map.addOverlay(marker);
                        
                        // 为标记点添加点击事件
                        marker.addEventListener('click', function() {
                            infoWindow.setContent(infoContent);
                            map.openInfoWindow(infoWindow, cityPoint);
                        });
                        
                        // 创建信息窗口内容（点击时显示）
                        const infoWindow = new BMap.InfoWindow('', {
                            width: 300,
                            height: 365
                        });
                        
                        // 创建信息窗口HTML内容
                        const infoContent = document.createElement('div');
                        infoContent.className = 'map-info-window';
                        
                        // 标题
                        const title = document.createElement('div');
                        title.className = 'map-info-title';
                        title.textContent = `${cityIndex + 1}. ${city.chineseName || city.name}`; // 添加序号
                        infoContent.appendChild(title);
                        
                        // 当前天气
                        if (currentData.temps.length > 0) {
                            const todayTemp = currentData.temps[0];
                            const todayWeatherCode = currentData.weatherCodes[0];
                            const weatherInfo = weatherCodeMap[todayWeatherCode] || { text: "未知天气", icon: "❓" };
                            
                            const weatherIcon = document.createElement('div');
                            weatherIcon.className = 'map-weather-icon';
                            weatherIcon.textContent = weatherInfo.icon;
                            infoContent.appendChild(weatherIcon);
                            
                            const weatherText = document.createElement('div');
                            weatherText.className = 'map-temperature';
                            weatherText.textContent = weatherInfo.text;
                            infoContent.appendChild(weatherText);
                            
                            const tempText = document.createElement('div');
                            tempText.className = 'map-temperature';
                            tempText.textContent = `最高: ${Math.round(todayTemp.max)}°C / 最低: ${Math.round(todayTemp.min)}°C`;
                            infoContent.appendChild(tempText);
                        }
                        
                        // 图表容器
                        const chartContainer = document.createElement('div');
                        chartContainer.className = 'map-chart-container';
                        infoContent.appendChild(chartContainer);
                        
                        // 控制按钮
                        const controls = document.createElement('div');
                        controls.className = 'map-controls';
                        
                        const trendBtn = document.createElement('button');
                        trendBtn.textContent = '查看趋势';
                        trendBtn.addEventListener('click', () => {
                            // 切换到趋势标签页
                            document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
                            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
                            
                            document.querySelector('.tab-button[data-tab="trend"]').classList.add('active');
                            document.getElementById('trend-tab').classList.add('active');
                            
                            // 滚动到对应城市的图表
                            setTimeout(() => {
                                const chartCards = document.querySelectorAll('.chart-card');
                                if (chartCards[cityIndex]) {
                                    chartCards[cityIndex].scrollIntoView({ behavior: 'smooth', block: 'center' });
                                }
                            }, 100);
                        });
                        
                        const listBtn = document.createElement('button');
                        listBtn.textContent = '查看详情';
                        listBtn.addEventListener('click', () => {
                            // 切换到列表标签页
                            document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
                            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
                            
                            document.querySelector('.tab-button[data-tab="list"]').classList.add('active');
                            document.getElementById('list-tab').classList.add('active');
                        });
                        
                        controls.appendChild(trendBtn);
                        controls.appendChild(listBtn);
                        infoContent.appendChild(controls);
                        
                        // 创建图表
                        setTimeout(() => {
                            const dates = getDateRange(
                                document.getElementById('startDate').value,
                                document.getElementById('endDate').value
                            );
                            
                            const currentMaxTemps = currentData.temps.map(temp => Math.round(temp.max));
                            const currentMinTemps = currentData.temps.map(temp => Math.round(temp.min));
                            
                            // 检测气温骤降
                            const hasSuddenDrop = hasTemperatureSuddenDrop(currentData.temps);
                            
                            const canvas = document.createElement('canvas');
                            chartContainer.appendChild(canvas);
                            
                            new Chart(canvas, {
                                type: 'line',
                                data: {
                                    labels: dates,
                                    datasets: [
                                        {
                                            label: '最高温度',
                                            data: currentMaxTemps,
                                            borderColor: 'rgb(255, 99, 132)',
                                            backgroundColor: 'rgba(255, 99, 132, 0.1)',
                                            tension: 0.3,
                                            yAxisID: 'y'
                                        },
                                        {
                                            label: '最低温度',
                                            data: currentMinTemps,
                                            borderColor: 'rgb(54, 162, 235)',
                                            backgroundColor: 'rgba(54, 162, 235, 0.1)',
                                            tension: 0.3,
                                            yAxisID: 'y'
                                        }
                                    ]
                                },
                                options: {
                                    responsive: true,
                                    maintainAspectRatio: false,
                                    plugins: {
                                        title: {
                                            display: true,
                                            text: '温度趋势' + (hasSuddenDrop ? ' (⚠️ 气温骤降警告)' : '')
                                        },
                                        legend: {
                                            display: true,
                                            position: 'top'
                                        }
                                    },
                                    scales: {
                                        x: {
                                            display: false,
                                            title: {
                                                display: true,
                                                text: '日期'
                                            }
                                        },
                                        y: {
                                            display: true,
                                            title: {
                                                display: true,
                                                text: '温度 (°C)'
                                            }
                                        }
                                    }
                                }
                            });
                        }, 100);
                        
                        // 点击标记打开信息窗口
                        marker.addEventListener('click', () => {
                            map.openInfoWindow(infoWindow, cityPoint);
                            infoWindow.setContent(infoContent);
                        });
                    });
                    
                    // 隐藏加载状态
                    mapLoading.style.display = 'none';
                } catch (error) {
                    console.error('渲染地图时出错:', error);
                    mapLoading.style.display = 'none';
                    showMessage('加载地图时出错: ' + error.message, 'error');
                }
            }, 100);
        }

        // 导出配置为Excel
        function exportConfig() {
            try {
                // 准备数据
                const data = cities.map(city => ({
                    '国家': city.country || '',
                    '省份': city.admin1 || '',
                    '城市': city.admin2 || '',
                    '地区': city.name,
                    '中文地区': city.chineseName || city.name,
                    '经度': city.lon,
                    '纬度': city.lat
                }));
                
                // 创建工作簿
                const wb = XLSX.utils.book_new();
                const ws = XLSX.utils.json_to_sheet(data);
                
                // 将工作表添加到工作簿
                XLSX.utils.book_append_sheet(wb, ws, '城市配置');
                
                // 生成Excel文件并下载
                XLSX.writeFile(wb, '城市天气配置.xlsx');
                
                showMessage('配置已成功导出为Excel文件', 'success');
            } catch (error) {
                console.error('导出配置时出错:', error);
                showMessage('导出配置时出错: ' + error.message, 'error');
            }
        }

        // 导出温度数据为Excel
        function exportTemperatureData() {
            try {
                // 检查是否有天气数据
                if (!currentWeatherData || currentWeatherData.length === 0) {
                    showMessage('请先加载天气数据再导出', 'error');
                    return;
                }
                
                // 准备数据
                const data = [];
                
                // 使用第一个城市的数据日期作为基准（所有城市应该返回相同的日期范围）
                const baseData = currentWeatherData.find(data => data && data.dates);
                if (!baseData) {
                    showMessage('没有可用的日期数据', 'error');
                    return;
                }
                
                const dates = baseData.dates;
                
                // 为每个日期创建一行数据
                dates.forEach((date, dateIndex) => {
                    const row = {
                        '日期': date
                    };
                    
                    // 为每个城市添加温度数据
                    cities.forEach((city, cityIndex) => {
                        const cityData = currentWeatherData[cityIndex];
                        if (cityData && cityData.temps && dateIndex < cityData.temps.length) {
                            const maxTemp = Math.round(cityData.temps[dateIndex].max);
                            const minTemp = Math.round(cityData.temps[dateIndex].min);
                            row[`${city.chineseName || city.name} 最高温度(°C)`] = maxTemp;
                            row[`${city.chineseName || city.name} 最低温度(°C)`] = minTemp;
                        } else {
                            row[`${city.chineseName || city.name} 最高温度(°C)`] = '';
                            row[`${city.chineseName || city.name} 最低温度(°C)`] = '';
                        }
                    });
                    
                    data.push(row);
                });
                
                // 创建工作簿
                const wb = XLSX.utils.book_new();
                const ws = XLSX.utils.json_to_sheet(data);
                
                // 将工作表添加到工作簿
                XLSX.utils.book_append_sheet(wb, ws, '温度数据');
                
                // 生成Excel文件并下载
                XLSX.writeFile(wb, '温度数据.xlsx');
                
                showMessage('温度数据已成功导出为Excel文件', 'success');
            } catch (error) {
                console.error('导出温度数据时出错:', error);
                showMessage('导出温度数据时出错: ' + error.message, 'error');
            }
        }

        // 导出天气数据为Excel
        function exportWeatherData() {
            try {
                // 检查是否有天气数据
                if (!currentWeatherData || currentWeatherData.length === 0) {
                    showMessage('请先加载天气数据再导出', 'error');
                    return;
                }
                
                // 准备数据
                const data = [];
                
                // 使用第一个城市的数据日期作为基准（所有城市应该返回相同的日期范围）
                const baseData = currentWeatherData.find(data => data && data.dates);
                if (!baseData) {
                    showMessage('没有可用的日期数据', 'error');
                    return;
                }
                
                const dates = baseData.dates;
                
                // 为每个日期创建一行数据
                dates.forEach((date, dateIndex) => {
                    const row = {
                        '日期': date
                    };
                    
                    // 为每个城市添加天气和温度数据
                    cities.forEach((city, cityIndex) => {
                        const cityData = currentWeatherData[cityIndex];
                        if (cityData && cityData.temps && cityData.weatherCodes && dateIndex < cityData.temps.length) {
                            const maxTemp = Math.round(cityData.temps[dateIndex].max);
                            const minTemp = Math.round(cityData.temps[dateIndex].min);
                            const weatherCode = cityData.weatherCodes[dateIndex];
                            const weatherInfo = weatherCodeMap[weatherCode] || { text: "未知天气", icon: "❓" };
                            
                            row[`${city.chineseName || city.name} 最高温度(°C)`] = maxTemp;
                            row[`${city.chineseName || city.name} 最低温度(°C)`] = minTemp;
                            row[`${city.chineseName || city.name} 天气状况`] = weatherInfo.text;
                            row[`${city.chineseName || city.name} 天气图标`] = weatherInfo.icon;
                        } else {
                            row[`${city.chineseName || city.name} 最高温度(°C)`] = '';
                            row[`${city.chineseName || city.name} 最低温度(°C)`] = '';
                            row[`${city.chineseName || city.name} 天气状况`] = '';
                            row[`${city.chineseName || city.name} 天气图标`] = '';
                        }
                    });
                    
                    data.push(row);
                });
                
                // 创建工作簿
                const wb = XLSX.utils.book_new();
                const ws = XLSX.utils.json_to_sheet(data);
                
                // 将工作表添加到工作簿
                XLSX.utils.book_append_sheet(wb, ws, '天气数据');
                
                // 生成Excel文件并下载
                XLSX.writeFile(wb, '天气数据.xlsx');
                
                showMessage('天气数据已成功导出为Excel文件', 'success');
            } catch (error) {
                console.error('导出天气数据时出错:', error);
                showMessage('导出天气数据时出错: ' + error.message, 'error');
            }
        }

        // 导入配置
        function importConfig(file) {
            try {
                const reader = new FileReader();
                
                reader.onload = function(e) {
                    try {
                        const data = new Uint8Array(e.target.result);
                        const workbook = XLSX.read(data, { type: 'array' });
                        
                        // 获取第一个工作表
                        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
                        const jsonData = XLSX.utils.sheet_to_json(worksheet);
                        
                        // 验证数据格式
                        const validData = jsonData.filter(item => 
                            item['地区'] && 
                            !isNaN(parseFloat(item['经度'])) && 
                            !isNaN(parseFloat(item['纬度']))
                        );
                        
                        if (validData.length === 0) {
                            showMessage('导入的文件中没有有效的城市数据', 'error');
                            return;
                        }
                        
                        // 转换为城市对象
                        const importedCities = validData.map(item => ({
                            name: item['地区'],
                            lat: parseFloat(item['纬度']),
                            lon: parseFloat(item['经度']),
                            country: item['国家'] || '',
                            admin1: item['省份'] || '',
                            admin2: item['城市'] || '',
                            chineseName: item['中文地区'] || item['地区']
                        }));
                        
                        // 更新城市列表
                        cities = importedCities;
                        saveCities(cities);
                        
                        // 重新初始化界面
                        initTableHeader();
                        initTableBody();
                        initConfigTable();
                        
                        showMessage(`成功导入 ${importedCities.length} 个城市`, 'success');
                    } catch (error) {
                        console.error('解析导入文件时出错:', error);
                        showMessage('解析导入文件时出错: ' + error.message, 'error');
                    }
                };
                
                reader.readAsArrayBuffer(file);
            } catch (error) {
                console.error('导入配置时出错:', error);
                showMessage('导入配置时出错: ' + error.message, 'error');
            }
        }

        // 请求单个城市的天气数据
        async function fetchCityWeather(city, startDate, endDate, isFuture) {
            if (isFuture) {
                return await fetchForecastWeather(city, startDate, endDate);
            } else {
                return await fetchHistoricalWeather(city, startDate, endDate);
            }
        }

        // 获取历史天气数据
        async function fetchHistoricalWeather(city, startDate, endDate) {
            // 使用GMT时区而不是UTC，避免时区差异导致日期不匹配
            const apiUrl = `https://archive-api.open-meteo.com/v1/archive?latitude=${city.lat}&longitude=${city.lon}&daily=temperature_2m_max,temperature_2m_min,weathercode&timezone=GMT&start_date=${startDate}&end_date=${endDate}`;
            
            try {
                const response = await fetch(apiUrl);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const data = await response.json();
                
                if (data.daily && data.daily.time) {
                    return {
                        name: city.name,
                        dates: data.daily.time, // 返回API的实际日期
                        temps: data.daily.temperature_2m_max.map((max, i) => ({
                            max,
                            min: data.daily.temperature_2m_min[i]
                        })),
                        weatherCodes: data.daily.weathercode
                    };
                } else {
                    throw new Error('API返回数据格式不正确');
                }
            } catch (error) {
                console.error(`获取 ${city.name} 历史天气数据失败:`, error);
                throw error;
            }
        }

        // 获取天气预报数据
        async function fetchForecastWeather(city, startDate, endDate) {
            // 计算预报天数
            const start = new Date(startDate);
            const end = new Date(endDate);
            const forecastDays = Math.ceil((end - start) / (1000 * 60 * 60 * 24)) + 1;
            
            // 使用GMT时区而不是UTC，避免时区差异导致日期不匹配
            const apiUrl = `https://api.open-meteo.com/v1/forecast?latitude=${city.lat}&longitude=${city.lon}&daily=temperature_2m_max,temperature_2m_min,weathercode&timezone=GMT&forecast_days=${forecastDays}`;
            
            try {
                const response = await fetch(apiUrl);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const data = await response.json();
                
                if (data.daily && data.daily.time) {
                    // 由于时区差异，API返回的日期可能与请求日期有1天的偏移
                    // 使用更灵活的方式匹配日期，而不是严格的indexOf
                    let startIndex = -1;
                    let endIndex = -1;
                    
                    // 查找最接近的日期匹配
                    for (let i = 0; i < data.daily.time.length; i++) {
                        const apiDate = data.daily.time[i];
                        
                        // 如果找到匹配的开始日期
                        if (startIndex === -1 && (apiDate === startDate || apiDate >= startDate)) {
                            startIndex = i;
                        }
                        
                        // 如果找到匹配的结束日期
                        if (apiDate === endDate || apiDate <= endDate) {
                            endIndex = i;
                        } else if (apiDate > endDate) {
                            break;
                        }
                    }
                    
                    // 如果找不到精确匹配，使用第一个和最后一个日期
                    if (startIndex === -1) startIndex = 0;
                    if (endIndex === -1) endIndex = data.daily.time.length - 1;
                    
                    // 确保索引有效
                    if (startIndex > endIndex) {
                        // 如果开始索引大于结束索引，交换它们
                        [startIndex, endIndex] = [endIndex, startIndex];
                    }
                    
                    // 确保索引在有效范围内
                    startIndex = Math.max(0, Math.min(startIndex, data.daily.time.length - 1));
                    endIndex = Math.max(0, Math.min(endIndex, data.daily.time.length - 1));
                    
                    console.log(`日期匹配: 请求 ${startDate} 到 ${endDate}, API返回 ${data.daily.time[startIndex]} 到 ${data.daily.time[endIndex]}`);
                    
                    return {
                        name: city.name,
                        dates: data.daily.time.slice(startIndex, endIndex + 1), // 返回API的实际日期
                        temps: data.daily.temperature_2m_max.slice(startIndex, endIndex + 1).map((max, i) => ({
                            max,
                            min: data.daily.temperature_2m_min[startIndex + i]
                        })),
                        weatherCodes: data.daily.weathercode.slice(startIndex, endIndex + 1)
                    };
                } else {
                    throw new Error('API返回数据格式不正确');
                }
            } catch (error) {
                console.error(`获取 ${city.name} 天气预报数据失败:`, error);
                throw error;
            }
        }

        // 通过地理编码API搜索城市
        async function searchCities(query) {
            const apiUrl = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(query)}&count=5&language=en&format=json`;
            try {
                const response = await fetch(apiUrl);
                const data = await response.json();
                
                if (data.results && data.results.length > 0) {
                    return data.results;
                } else {
                    return [];
                }
            } catch (error) {
                console.error(`搜索城市失败:`, error);
                return [];
            }
        }

        // 显示自动完成列表
        function showAutocompleteList(cities) {
            const autocompleteList = document.getElementById('autocompleteList');
            autocompleteList.innerHTML = '';
            
            if (cities.length === 0) {
                autocompleteList.style.display = 'none';
                return;
            }
            
            cities.forEach(city => {
                const item = document.createElement('div');
                item.className = 'autocomplete-item';
                
                // 确定城市显示名称，如果admin2为空则使用name
                const cityDisplayName = city.admin2 || city.name;
                
                item.innerHTML = `
                    <div class="city-info">
                        <div class="city-name">${city.name}</div>
                        <div class="city-details">国家: ${city.country || '未知'} | 省份: ${city.admin1 || '未知'} | 城市: ${cityDisplayName} | 经度: ${city.longitude.toFixed(2)} | 纬度: ${city.latitude.toFixed(2)}</div>
                    </div>
                `;
                
                item.addEventListener('click', () => {
                    document.getElementById('cityInput').value = city.name;
                    autocompleteList.style.display = 'none';
                    // 直接添加选中的城市
                    addCityByObject({
                        name: city.name,
                        lat: city.latitude,
                        lon: city.longitude,
                        country: city.country,
                        admin1: city.admin1,
                        admin2: city.admin2 || city.name // 如果admin2为空，使用name
                    });
                });
                
                autocompleteList.appendChild(item);
            });
            
            autocompleteList.style.display = 'block';
        }

        // 添加城市（通过城市对象）
        async function addCityByObject(cityData) {
            // 检查是否已存在
            if (cities.some(city => city.name.toLowerCase() === cityData.name.toLowerCase())) {
                showMessage(`城市 "${cityData.name}" 已存在`, 'error');
                return;
            }
            
            // 添加到城市列表
            cities.push(cityData);
            saveCities(cities);
            
            // 重新初始化界面
            initTableHeader();
            initTableBody();
            initConfigTable();
            
            showMessage(`成功添加城市 "${cityData.name}"`, 'success');
            document.getElementById('cityInput').value = '';
        }

        // 添加城市（通过城市名称）
        async function addCity(cityName) {
            // 检查是否已存在
            if (cities.some(city => city.name.toLowerCase() === cityName.toLowerCase())) {
                showMessage(`城市 "${cityName}" 已存在`, 'error');
                return;
            }
            
            try {
                showMessage(`正在查找城市 "${cityName}"...`, 'success');
                const cityData = await getCityCoordinates(cityName);
                
                // 添加到城市列表
                cities.push(cityData);
                saveCities(cities);
                
                // 重新初始化界面
                initTableHeader();
                initTableBody();
                initConfigTable();
                
                showMessage(`成功添加城市 "${cityData.name}"`, 'success');
                document.getElementById('cityInput').value = '';
            } catch (error) {
                showMessage(`添加城市失败: ${error.message}`, 'error');
            }
        }

        // 通过地理编码API获取城市经纬度
        async function getCityCoordinates(cityName) {
            const apiUrl = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(cityName)}&count=1&language=en&format=json`;
            try {
                const response = await fetch(apiUrl);
                const data = await response.json();
                
                if (data.results && data.results.length > 0) {
                    const city = data.results[0];
                    return {
                        name: city.name,
                        lat: city.latitude,
                        lon: city.longitude,
                        country: city.country,
                        admin1: city.admin1,
                        admin2: city.admin2 || city.name // 如果admin2为空，使用name
                    };
                } else {
                    throw new Error('未找到该城市');
                }
            } catch (error) {
                console.error(`获取 ${cityName} 经纬度失败:`, error);
                throw error;
            }
        }

        // 删除城市
        function deleteCity(cityName) {
            if (cities.length <= 1) {
                showMessage('至少需要保留一个城市', 'error');
                return;
            }
            
            cities = cities.filter(city => city.name !== cityName);
            saveCities(cities);
            
            // 重新初始化界面
            initTableHeader();
            initTableBody();
            initConfigTable();
            
            showMessage(`已删除城市 "${cityName}"`, 'success');
        }

        // 重置为默认城市
        function resetToDefaultCities() {
            cities = [...defaultCities];
            saveCities(cities);
            
            // 重新初始化界面
            initTableHeader();
            initTableBody();
            initConfigTable();
            
            showMessage('已重置为默认城市列表', 'success');
        }

        // 设置日期范围
        function setDateRange(startDate, endDate) {
            document.getElementById('startDate').value = startDate;
            document.getElementById('endDate').value = endDate;
            initTableBody();
        }

        // 初始化日期控件
        function initDateControls() {
            const today = new Date();
            const next15Days = new Date();
            next15Days.setDate(today.getDate() + 14);
            
            // 设置默认日期范围为未来15天
            document.getElementById('startDate').value = formatDate(today);
            document.getElementById('endDate').value = formatDate(next15Days);
            
            // 添加日期预设按钮事件
            document.getElementById('todayBtn').addEventListener('click', () => {
                const today = formatDate(new Date());
                setDateRange(today, today);
            });
            
            document.getElementById('next7DaysBtn').addEventListener('click', () => {
                const start = new Date();
                const end = new Date();
                end.setDate(start.getDate() + 6);
                setDateRange(formatDate(start), formatDate(end));
            });
            
            document.getElementById('next15DaysBtn').addEventListener('click', () => {
                const start = new Date();
                const end = new Date();
                end.setDate(start.getDate() + 14);
                setDateRange(formatDate(start), formatDate(end));
            });
            
            document.getElementById('past7DaysBtn').addEventListener('click', () => {
                const end = new Date();
                end.setDate(end.getDate() - 1); // 昨天
                const start = new Date();
                start.setDate(end.getDate() - 6);
                setDateRange(formatDate(start), formatDate(end));
            });
            
            document.getElementById('past30DaysBtn').addEventListener('click', () => {
                const end = new Date();
                end.setDate(end.getDate() - 1); // 昨天
                const start = new Date();
                start.setDate(end.getDate() - 29);
                setDateRange(formatDate(start), formatDate(end));
            });
            
            // 更新日期范围按钮
            document.getElementById('updateDatesBtn').addEventListener('click', initTableBody);
            
            // 对比去年复选框事件
            document.getElementById('compareLastYear').addEventListener('change', () => {
                initTableHeader();
                initTableBody();
            });
        }

        // 初始化Tab控件
        function initTabs() {
            const tabButtons = document.querySelectorAll('.tab-button');
            const tabContents = document.querySelectorAll('.tab-content');
            
            tabButtons.forEach(button => {
                button.addEventListener('click', () => {
                    // 移除所有active类
                    tabButtons.forEach(btn => btn.classList.remove('active'));
                    tabContents.forEach(content => content.classList.remove('active'));
                    
                    // 添加active类到当前按钮和内容
                    button.classList.add('active');
                    const tabId = button.dataset.tab + '-tab';
                    document.getElementById(tabId).classList.add('active');
                    
                    // 如果切换到趋势标签页，渲染图表
                    if (button.dataset.tab === 'trend') {
                        renderTrendCharts();
                    }
                    
                    // 如果切换到地图标签页，渲染地图
                    if (button.dataset.tab === 'map') {
                        renderMap();
                    }
                    
                    // 如果切换到配置标签页，更新配置表格
                    if (button.dataset.tab === 'config') {
                        initConfigTable();
                    }
                    
                    // 如果切换到分析标签页，自动执行分析
                    if (button.dataset.tab === 'analysis') {
                        if (currentWeatherData && currentWeatherData.length > 0) {
                            performAnalysis();
                        }
                    }
                });
            });
        }

        // 初始化应用
        function initApp() {
            // 从localStorage获取城市列表
            cities = getCities();
            
            // 初始化日期控件
            initDateControls();
            
            // 初始化Tab控件
            initTabs();
            
            // 初始化分析页面
            initAnalysisPage();
            
            // 初始化配置表格
            initConfigTable();
            
            // 初始化表格
            initTableHeader();
            initTableBody();
            
            // 添加事件监听器
            document.getElementById('addCityBtn').addEventListener('click', () => {
                const cityName = document.getElementById('cityInput').value.trim();
                if (cityName) {
                    addCity(cityName);
                } else {
                    showMessage('请输入城市名称', 'error');
                }
            });
            
            document.getElementById('cityInput').addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    const cityName = document.getElementById('cityInput').value.trim();
                    if (cityName) {
                        addCity(cityName);
                    } else {
                        showMessage('请输入城市名称', 'error');
                    }
                }
            });
            
            document.getElementById('resetCitiesBtn').addEventListener('click', resetToDefaultCities);
            
            // 导出配置按钮
            document.getElementById('exportConfigBtn').addEventListener('click', exportConfig);
            
            // 导出温度数据按钮
            document.getElementById('exportTempDataBtn').addEventListener('click', exportTemperatureData);
            
            // 导出天气数据按钮
            document.getElementById('exportWeatherDataBtn').addEventListener('click', exportWeatherData);
            
            // 导入配置按钮
            document.getElementById('importConfigBtn').addEventListener('click', () => {
                document.getElementById('configFileInput').click();
            });
            
            // 文件选择事件
            document.getElementById('configFileInput').addEventListener('change', (e) => {
                const file = e.target.files[0];
                if (file) {
                    importConfig(file);
                }
                // 重置文件输入，允许再次选择同一文件
                e.target.value = '';
            });
            
            // 自动完成功能
            let searchTimeout;
            document.getElementById('cityInput').addEventListener('input', (e) => {
                const query = e.target.value.trim();
                
                if (query.length < 2) {
                    document.getElementById('autocompleteList').style.display = 'none';
                    return;
                }
                
                // 清除之前的定时器
                clearTimeout(searchTimeout);
                
                // 设置新的定时器，延迟搜索
                searchTimeout = setTimeout(async () => {
                    const results = await searchCities(query);
                    showAutocompleteList(results);
                }, 300);
            });
            
            // 点击页面其他地方时隐藏自动完成列表
            document.addEventListener('click', (e) => {
                if (!e.target.closest('.autocomplete-container')) {
                    document.getElementById('autocompleteList').style.display = 'none';
                }
            });
        }

        // 全局变量
        let cities = [];
        let currentWeatherData = [];
        let lastYearWeatherData = null;
        
        // 分析页面相关变量
        let tempRanges = [];
        let analysisSettings = {
            maxTempPercentile: 85,
            minTempPercentile: 85
        };
        
        // ==============================================
        // 分析页面功能
        // ==============================================
        
        // 默认温度带配置
        const defaultTempRanges = [
            { id: 1, name: '0度以下', min: -Infinity, max: 0 },
            { id: 2, name: '0-5度', min: 0, max: 5 },
            { id: 3, name: '5度以上', min: 5, max: Infinity }
        ];
        
        // 从 localStorage 加载温度带配置
        function loadTempRanges() {
            const saved = localStorage.getItem('weatherAnalysisTempRanges');
            if (saved) {
                try {
                    tempRanges = JSON.parse(saved);
                } catch (e) {
                    console.error('加载温度带配置失败:', e);
                    tempRanges = [...defaultTempRanges];
                }
            } else {
                tempRanges = [...defaultTempRanges];
            }
        }
        
        // 保存温度带配置到 localStorage
        function saveTempRanges() {
            localStorage.setItem('weatherAnalysisTempRanges', JSON.stringify(tempRanges));
        }
        
        // 从 localStorage 加载分析设置
        function loadAnalysisSettings() {
            const saved = localStorage.getItem('weatherAnalysisSettings');
            if (saved) {
                try {
                    analysisSettings = JSON.parse(saved);
                    document.getElementById('maxTempPercentile').value = analysisSettings.maxTempPercentile;
                    document.getElementById('minTempPercentile').value = analysisSettings.minTempPercentile;
                } catch (e) {
                    console.error('加载分析设置失败:', e);
                }
            }
        }
        
        // 保存分析设置到 localStorage
        function saveAnalysisSettings() {
            analysisSettings.maxTempPercentile = parseInt(document.getElementById('maxTempPercentile').value);
            analysisSettings.minTempPercentile = parseInt(document.getElementById('minTempPercentile').value);
            localStorage.setItem('weatherAnalysisSettings', JSON.stringify(analysisSettings));
        }
        
        // 渲染温度带配置界面
        function renderTempRanges() {
            const container = document.getElementById('tempRangesContainer');
            container.innerHTML = '';
            
            // 按最小值排序
            tempRanges.sort((a, b) => {
                if (a.min === -Infinity) return -1;
                if (b.min === -Infinity) return 1;
                return a.min - b.min;
            });
            
            tempRanges.forEach((range, index) => {
                const item = document.createElement('div');
                item.className = 'temp-range-item';
                
                const minValue = range.min === -Infinity ? '' : range.min;
                const maxValue = range.max === Infinity ? '' : range.max;
                
                item.innerHTML = `
                    <label>温度带名称:</label>
                    <input type="text" value="${range.name}" data-index="${index}" data-field="name">
                    <div style="display: flex; gap: 10px; margin-top: 10px;">
                        <div style="flex: 1;">
                            <label>最小值 (°C):</label>
                            <input type="number" value="${minValue}" data-index="${index}" data-field="min" 
                                   placeholder="无限小" step="0.1">
                        </div>
                        <div style="flex: 1;">
                            <label>最大值 (°C):</label>
                            <input type="number" value="${maxValue}" data-index="${index}" data-field="max" 
                                   placeholder="无限大" step="0.1">
                        </div>
                    </div>
                    ${tempRanges.length > 1 ? `<button class="btn-remove" data-index="${index}">删除</button>` : ''}
                `;
                
                container.appendChild(item);
            });
            
            // 添加事件监听
            container.querySelectorAll('input').forEach(input => {
                input.addEventListener('change', updateTempRange);
            });
            
            container.querySelectorAll('.btn-remove').forEach(btn => {
                btn.addEventListener('click', removeTempRange);
            });
        }
        
        // 更新温度带配置
        function updateTempRange(e) {
            const index = parseInt(e.target.dataset.index);
            const field = e.target.dataset.field;
            let value = e.target.value.trim();
            
            if (field === 'name') {
                tempRanges[index][field] = value;
            } else {
                if (value === '') {
                    tempRanges[index][field] = field === 'min' ? -Infinity : Infinity;
                } else {
                    tempRanges[index][field] = parseFloat(value);
                }
            }
            
            saveTempRanges();
        }
        
        // 删除温度带
        function removeTempRange(e) {
            const index = parseInt(e.target.dataset.index);
            tempRanges.splice(index, 1);
            saveTempRanges();
            renderTempRanges();
        }
        
        // 添加温度带
        function addTempRange() {
            const newId = Math.max(0, ...tempRanges.map(r => r.id)) + 1;
            tempRanges.push({
                id: newId,
                name: `温度带 ${newId}`,
                min: 0,
                max: 10
            });
            saveTempRanges();
            renderTempRanges();
        }
        
        // 恢复默认温度带
        function resetTempRanges() {
            tempRanges = [...defaultTempRanges];
            saveTempRanges();
            renderTempRanges();
            showMessage('已恢夏默认温度带配置', 'success');
        }
        
        // 计算百分位数
        function calculatePercentile(values, percentile) {
            if (values.length === 0) return null;
            
            const sorted = [...values].sort((a, b) => a - b);
            const index = (percentile / 100) * (sorted.length - 1);
            const lower = Math.floor(index);
            const upper = Math.ceil(index);
            const weight = index - lower;
            
            return sorted[lower] * (1 - weight) + sorted[upper] * weight;
        }
        
        // 分析单个城市的天气数据
        function analyzeCityWeather(cityData) {
            if (!cityData || !cityData.temps || cityData.temps.length === 0) {
                return null;
            }
            
            const maxTemps = cityData.temps.map(t => t.max);
            const minTemps = cityData.temps.map(t => t.min);
            
            // 计算百分位数
            const maxTempPercentile = calculatePercentile(maxTemps, analysisSettings.maxTempPercentile);
            const minTempPercentile = calculatePercentile(minTemps, analysisSettings.minTempPercentile);
            
            // 统计各温度带的天数
            // 首先对温度带按照最小值排序
            const sortedRanges = [...tempRanges].sort((a, b) => {
                if (a.min === -Infinity) return -1;
                if (b.min === -Infinity) return 1;
                if (a.min === b.min) return 0;
                return a.min - b.min;
            });
            
            const rangeStats = sortedRanges.map((range, rangeIndex) => {
                let days = 0;
                cityData.temps.forEach(temp => {
                    const minTemp = temp.min;
                    
                    // 判断是否属于当前温度带
                    let inRange = false;
                    
                    if (range.min === -Infinity && range.max === Infinity) {
                        // 覆盖所有温度
                        inRange = true;
                    } else if (range.min === -Infinity) {
                        // 无下限，只有上限：使用 < 不包含上界
                        inRange = minTemp < range.max;
                    } else if (range.max === Infinity) {
                        // 无上限，只有下限：使用 >= 包含下界
                        inRange = minTemp >= range.min;
                    } else {
                        // 有上下限：下界包含，上界不包含（左闭右开区间）
                        // 这样可以确保每个值只属于一个区间
                        inRange = minTemp >= range.min && minTemp < range.max;
                    }
                    
                    if (inRange) {
                        days++;
                    }
                });
                
                return {
                    name: range.name,
                    days: days,
                    percentage: (days / cityData.temps.length * 100).toFixed(1)
                };
            });
            
            // 验证统计完整性：检查是否所有数据都被统计
            const totalCounted = rangeStats.reduce((sum, stat) => sum + stat.days, 0);
            if (totalCounted !== cityData.temps.length) {
                console.warn('⚠️ 温度带统计不完整:');
                console.warn(`  总天数: ${cityData.temps.length}`);
                console.warn(`  已统计: ${totalCounted}`);
                console.warn(`  遗漏: ${cityData.temps.length - totalCounted}`);
                
                // 找出未被统计的温度值
                const uncountedTemps = [];
                cityData.temps.forEach((temp, index) => {
                    let counted = false;
                    for (const range of sortedRanges) {
                        const minTemp = temp.min;
                        let inRange = false;
                        
                        if (range.min === -Infinity && range.max === Infinity) {
                            inRange = true;
                        } else if (range.min === -Infinity) {
                            inRange = minTemp < range.max;
                        } else if (range.max === Infinity) {
                            inRange = minTemp >= range.min;
                        } else {
                            inRange = minTemp >= range.min && minTemp < range.max;
                        }
                        
                        if (inRange) {
                            counted = true;
                            break;
                        }
                    }
                    
                    if (!counted) {
                        uncountedTemps.push({ index: index, minTemp: temp.min, maxTemp: temp.max });
                    }
                });
                
                if (uncountedTemps.length > 0) {
                    console.warn('  未统计的温度数据:', uncountedTemps);
                    console.warn('  当前温度带配置:', sortedRanges);
                }
            }
            
            return {
                totalDays: cityData.temps.length,
                maxTempPercentile: maxTempPercentile,
                minTempPercentile: minTempPercentile,
                rangeStats: rangeStats,
                avgMaxTemp: (maxTemps.reduce((a, b) => a + b, 0) / maxTemps.length).toFixed(1),
                avgMinTemp: (minTemps.reduce((a, b) => a + b, 0) / minTemps.length).toFixed(1)
            };
        }
        
        // 执行天气分析
        function performAnalysis() {
            // 保存设置
            saveAnalysisSettings();
            
            if (!currentWeatherData || currentWeatherData.length === 0) {
                showMessage('请先加载天气数据', 'error');
                return;
            }
            
            const resultsContainer = document.getElementById('analysisResults');
            resultsContainer.innerHTML = '';
            
            // 为每个城市生成分析报告
            cities.forEach((city, index) => {
                const cityData = currentWeatherData[index];
                const analysis = analyzeCityWeather(cityData);
                
                if (!analysis) {
                    return;
                }
                
                const cityCard = document.createElement('div');
                cityCard.className = 'city-analysis';
                
                // 计算总计
                const totalDays = analysis.rangeStats.reduce((sum, stat) => sum + stat.days, 0);
                const totalPercentage = analysis.rangeStats.reduce((sum, stat) => sum + parseFloat(stat.percentage), 0);
                const isComplete = totalDays === analysis.totalDays;
                
                cityCard.innerHTML = `
                    <h4>${city.chineseName || city.name}</h4>
                    
                    <div class="analysis-grid">
                        <div class="analysis-card">
                            <h5>📅 总天数</h5>
                            <div class="analysis-value">${analysis.totalDays} 天</div>
                        </div>
                        
                        <div class="analysis-card">
                            <h5>🌡️ 最高温${analysisSettings.maxTempPercentile}%值</h5>
                            <div class="analysis-value">${analysis.maxTempPercentile.toFixed(1)}°C</div>
                        </div>
                        
                        <div class="analysis-card">
                            <h5>❄️ 最低温${analysisSettings.minTempPercentile}%值</h5>
                            <div class="analysis-value">${analysis.minTempPercentile.toFixed(1)}°C</div>
                        </div>
                        
                        <div class="analysis-card">
                            <h5>📈 平均最高温</h5>
                            <div class="analysis-value">${analysis.avgMaxTemp}°C</div>
                        </div>
                        
                        <div class="analysis-card">
                            <h5>📉 平均最低温</h5>
                            <div class="analysis-value">${analysis.avgMinTemp}°C</div>
                        </div>
                    </div>
                    
                    <div class="temp-range-stats">
                        <h5>🌡️ 温度带分布</h5>
                        ${!isComplete ? `<div style="background: #fff3cd; border: 1px solid #ffc107; padding: 8px; margin-bottom: 10px; border-radius: 4px; color: #856404;">
                            ⚠️ 注意：温度带配置可能存在间隙，部分数据未被统计。请检查温度带设置是否覆盖所有温度范围。
                        </div>` : ''}
                        <table>
                            <thead>
                                <tr>
                                    <th>温度带</th>
                                    <th>天数</th>
                                    <th>占比</th>
                                    <th>分布</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${analysis.rangeStats.map(stat => {
                                    const percentage = parseFloat(stat.percentage);
                                    return `
                                    <tr>
                                        <td class="range-name">${stat.name}</td>
                                        <td>${stat.days} 天</td>
                                        <td>${stat.percentage}%</td>
                                        <td>
                                            <div class="progress-bar">
                                                <div class="progress-fill" style="width: ${stat.percentage}%">
                                                    ${percentage > 5 ? stat.percentage + '%' : ''}
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                `}).join('')}
                                <tr style="border-top: 2px solid #4CAF50; font-weight: bold; background-color: ${isComplete ? '#e8f5e9' : '#fff3cd'};">
                                    <td>总计</td>
                                    <td>${totalDays} 天</td>
                                    <td style="color: ${isComplete ? '#4CAF50' : '#ff9800'};">${totalPercentage.toFixed(1)}%</td>
                                    <td style="color: ${isComplete ? '#4CAF50' : '#ff9800'};">
                                        ${isComplete ? '✅ 完整' : `⚠️ 缺失 ${analysis.totalDays - totalDays} 天`}
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                `;
                
                resultsContainer.appendChild(cityCard);
            });
            
            showMessage('分析完成！', 'success');
        }
        
        // 初始化分析页面
        function initAnalysisPage() {
            loadTempRanges();
            loadAnalysisSettings();
            renderTempRanges();
            
            // 添加事件监听
            document.getElementById('addTempRangeBtn').addEventListener('click', addTempRange);
            document.getElementById('resetTempRangesBtn').addEventListener('click', resetTempRanges);
            document.getElementById('analyzeBtn').addEventListener('click', performAnalysis);
            
            // 百分位数输入框变化时自动重新分析
            document.getElementById('maxTempPercentile').addEventListener('change', () => {
                if (currentWeatherData && currentWeatherData.length > 0) {
                    performAnalysis();
                }
            });
            
            document.getElementById('minTempPercentile').addEventListener('change', () => {
                if (currentWeatherData && currentWeatherData.length > 0) {
                    performAnalysis();
                }
            });
        }

        // 页面加载完成后初始化应用
        document.addEventListener('DOMContentLoaded', initApp);
    </script>
    <!-- 百度地图API -->
    <script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=I8syxbzq4cKe7iy046E1OhhzFwJX8WHO"></script>
</body>
</html>